Android——SQLite實現物件導向CRUD

來源:互聯網
上載者:User

標籤:sqlite   crud   android   資料庫   單元測試   

        現在有點焦慮,不想寫代碼了,故而寫一下博文來放鬆一下。

        剛剛學了android中SQLite的使用,其實倒也不難,但是與JDBC操作資料庫相比,這個還是有點不順手,而且我好久沒寫底層的封裝了,使用SSM架構這些都不需要考慮......好了,廢話不多說,下面直接建立一個測試工程來試試SQLite在Android中的應用吧。


1、建立一個工程




2、配置junit測試環境

開啟AndroidManifest.xml檔案,進行jUnit相關配置,具體如:



3、源碼

        關於在Android中如何使用SQLite的文章很多,我也是參考那些文章進行學習的。作為一個J2EE方向的開發人員,我習慣於物件導向進行編程,而老羅的視頻以及一些其他的教程關於CRUD操作使用的都是字串,這我有點不適應,所有我在學習的過程中就改成了物件導向的CRUD操作,這樣用著也方便點。原理、API什麼的我就不說了,百度一下嗖嗖的都出來了,下面直接貼代碼(完整工程下載,點這裡):

      這樣一個繼承SQLiteOpenHelper的類主要就這麼幾個功能:

           a.建立資料庫和表

           b.如果資料庫有不同版本那麼就會更新資料庫

           c.調用的這個類的對象來取得資料庫的讀寫權限


package com.example.db;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;public class DBHelper extends SQLiteOpenHelper {private static final String DATABASE_NAME = "test.db";private static final int DATABASE_VERSION = 1;public DBHelper(Context context) {// CursorFactory設定為null,使用預設值super(context, DATABASE_NAME, null, DATABASE_VERSION);}// 資料庫第一次被建立時onCreate會被調用@Overridepublic void onCreate(SQLiteDatabase db) {String sql = "CREATE TABLE IF NOT EXISTS person "+ "(id INTEGER PRIMARY KEY AUTOINCREMENT,name VARCHAR(32),sex VARCHAR(8))";db.execSQL(sql);}// 如果DATABASE_VERSION值被改為2,系統發現現有資料庫版本不同,即會調用onUpgrade@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {db.execSQL("ALTER TABLE base_info ADD COLUMN other STRING");}}

可以看到上面建立了一個叫test.db的資料庫,其中有一個表person,表中有三個欄位:主鍵-id,姓名-name,性別-sex。


下面產生這個表對應的實體類:

package com.example.pojo;public class Person {private int id;private String name;private String sex;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}@Overridepublic String toString() {return "Person [id=" + id + ", name=" + name + ", sex=" + sex + "]";}}

我們要實現CRUD操作,那麼建一個介面定義CRUD方法:

package com.example.dao;import com.example.pojo.Person;public interface IPersonDao {public boolean insert(Person person);public boolean delete(int id);public boolean update(Person person);public Person select(int id);}

下面要實現IPersonDao介面,定義具體的業務方法:

package com.example.dao.impl;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import com.example.dao.IPersonDao;import com.example.db.DBHelper;import com.example.pojo.Person;public class PersonDaoImpl implements IPersonDao {DBHelper helper = null;public PersonDaoImpl(Context context){helper = new DBHelper(context);}@Overridepublic boolean insert(Person person) {boolean flag = false;SQLiteDatabase database = null;try {String sql = "INSERT INTO person(name,sex) VALUES (?,?)";database = helper.getWritableDatabase();database.execSQL(sql, new Object[]{person.getName(),person.getSex()});flag = true;} catch (Exception e) {e.printStackTrace();}finally{if(database!=null){database.close();}}return flag;}@Overridepublic boolean delete(int id) {boolean flag = false;SQLiteDatabase database = null;try {String sql = "DELETE FROM person WHERE id=?";database = helper.getWritableDatabase();database.execSQL(sql, new Object[]{Integer.toString(id)});flag = true;} catch (Exception e) {e.printStackTrace();}finally{if(database!=null){database.close();}}return flag;}@Overridepublic boolean update(Person person) {boolean flag = false;SQLiteDatabase database = null;try {String sql = "UPDATE person set name=? , sex=? where id=?";database = helper.getWritableDatabase();database.execSQL(sql, new Object[]{person.getName(),person.getSex(),person.getId()});flag = true;} catch (Exception e) {e.printStackTrace();}finally{if(database!=null){database.close();}}return flag;}@Overridepublic Person select(int id) {Person person = new Person();SQLiteDatabase database = null;try {String sql = "SELECT * FROM person where id=?";database = helper.getReadableDatabase();Cursor cursor = database.rawQuery(sql, new String[]{Integer.toString(id)});while(cursor.moveToNext()){int _id = cursor.getInt(cursor.getColumnIndex("id"));String _name = cursor.getString(cursor.getColumnIndex("name"));String _sex = cursor.getString(cursor.getColumnIndex("sex"));person.setId(_id);person.setName(_name);person.setSex(_sex);}} catch (Exception e) {e.printStackTrace();}finally{if(database!=null){database.close();}}return person;}}

以上完成之後就可以開始單元測試了,綠色......

package com.example.test;import com.example.dao.IPersonDao;import com.example.dao.impl.PersonDaoImpl;import com.example.pojo.Person;import android.test.AndroidTestCase;import android.util.Log;public class Test extends AndroidTestCase {public void insertDB(){IPersonDao personDao = new PersonDaoImpl(getContext());Person person = new Person();person.setName("李四");person.setSex("男");personDao.insert(person);}public void selectDB(){IPersonDao personDao = new PersonDaoImpl(getContext());Person person = personDao.select(1);Log.i("info", person.toString());}public void updateDB(){IPersonDao personDao = new PersonDaoImpl(getContext());Person person = personDao.select(1);person.setName("改名字啦");person.setSex("不詳");personDao.update(person);}public void deleteDB(){IPersonDao personDao = new PersonDaoImpl(getContext());personDao.delete(2);}}


匯出test.db檔案,在SQLite Expert中開啟:



這是insert測試成功的例子,其他就不放圖了,這個軟體百度就可以下載了。



(轉載註明出處:http://blog.csdn.net/zhshulin)

Android——SQLite實現物件導向CRUD

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.