目前所介紹的方法只是用來儲存一些簡單的資料。如果想要儲存關係型資料,那麼使用資料庫將會更加的效率。舉個例子,你要儲存學校裡面每一個學生的分數,這種情況下,最好使用資料庫,因為你可以查詢某個學生的具體分數。而且,使用資料庫能夠保持不同資料之間關係的完整性。
Android使用SQLite資料庫系統。使用這種資料庫,只有建立它的程式可以使用它,別的程式無法訪問到它。
在接下來的幾節中,會簡述如何通過編碼在你的程式中建立一個SQLite資料庫。對於Android來說,通過編碼建立的資料庫的儲存位置是/data/data/<packane_name>
/databases 。
想要處理資料庫的一種良好的方式就是建立一個資料庫輔助類,這個類中,封裝了所有的資料操作方式。因此,這節中我們來看看如何建立一個資料庫輔助類DBAdapter,這個類中包含建立,開啟,關閉和使用SQLite資料庫。
我們講建立一個資料庫,名字叫MyDB;包含一張表,名字叫contacts,有3列_id,name和email。
1. 建立一個工程,Databases。
2. 建立一個類,DBAdater。
3. DBAdapter.java中的代碼。
public class DBAdapter { static final String KEY_ROWID = "_id"; static final String KEY_NAME = "name"; static final String KEY_EMAIL = "email"; static final String TAG = "DBAdapter"; static final String DATABASE_NAME = "MyDB"; static final String DATABASE_TABLE = "contacts"; static final int DATABASE_VERSION = 2; static final String DATABASE_CREATE = "create table contacts (_id integer primary key autoincrement, " + "name text not null, email text not null);"; final Context context; DatabaseHelper DBHelper; SQLiteDatabase db; public DBAdapter(Context ctx) { this.context = ctx; DBHelper = new DatabaseHelper(context); } private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { try { db.execSQL(DATABASE_CREATE); } catch (SQLException e) { e.printStackTrace(); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS contacts"); onCreate(db); } } //---opens the database--- public DBAdapter open() throws SQLException { db = DBHelper.getWritableDatabase(); return this; } //---closes the database--- public void close() { DBHelper.close(); } //---insert a contact into the database--- public long insertContact(String name, String email) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_NAME, name); initialValues.put(KEY_EMAIL, email); return db.insert(DATABASE_TABLE, null, initialValues); } //---deletes a particular contact--- public boolean deleteContact(long rowId) { return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0; } //---retrieves all the contacts--- public Cursor getAllContacts() { return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME, KEY_EMAIL}, null, null, null, null, null); } //---retrieves a particular contact--- public Cursor getContact(long rowId) throws SQLException { Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME, KEY_EMAIL}, KEY_ROWID + "=" + rowId, null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } //---updates a contact--- public boolean updateContact(long rowId, String name, String email) { ContentValues args = new ContentValues(); args.put(KEY_NAME, name); args.put(KEY_EMAIL, email); return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0; }}
首先,聲明一些常量,包含一些表中所需要的欄位。
static final String KEY_ROWID = "_id"; static final String KEY_NAME = "name"; static final String KEY_EMAIL = "email"; static final String TAG = "DBAdapter"; static final String DATABASE_NAME = "MyDB"; static final String DATABASE_TABLE = "contacts"; static final int DATABASE_VERSION = 2; static final String DATABASE_CREATE = "create table contacts (_id integer primary key autoincrement, " + "name text not null, email text not null);";
在DBAdapter類中,添加了一個私人類,這個類繼承了SQLiteOpenHelper類,就是這個類去建立資料庫和進行資料庫的版本控制。通常重寫onCreate()和onUpgrade()方法:
private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { try { db.execSQL(DATABASE_CREATE); } catch (SQLException e) { e.printStackTrace(); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS contacts"); onCreate(db); } }
如果資料庫不存在的話,onCreate()方法會去建立一個新的資料庫。當資料庫需要升級的時候,onUpgrade()方法被調用。判斷資料庫是不是需要升級,需要去判斷DATABASE_VERSION常量。onUpgrade ()方法中實現很簡單,就是刪除表,然後重新建立它。
然後,定義資料的一些操作,開啟,關閉,增刪查改等。
//---opens the database--- public DBAdapter open() throws SQLException { db = DBHelper.getWritableDatabase(); return this; } //---closes the database--- public void close() { DBHelper.close(); } //---insert a contact into the database--- public long insertContact(String name, String email) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_NAME, name); initialValues.put(KEY_EMAIL, email); return db.insert(DATABASE_TABLE, null, initialValues); } //---deletes a particular contact--- public boolean deleteContact(long rowId) { return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0; } //---retrieves all the contacts--- public Cursor getAllContacts() { return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME, KEY_EMAIL}, null, null, null, null, null); } //---retrieves a particular contact--- public Cursor getContact(long rowId) throws SQLException { Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME, KEY_EMAIL}, KEY_ROWID + "=" + rowId, null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } //---updates a contact--- public boolean updateContact(long rowId, String name, String email) { ContentValues args = new ContentValues(); args.put(KEY_NAME, name); args.put(KEY_EMAIL, email); return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0; }
注意,Android使用Cursor類作為資料查詢的返回結果。把Curosr想象成查詢結果的指標。使用Cursor可以增加查詢的效率。
使用ContentValursObject Storage Service索引值對。
使用DBAdapter類去建立一個資料庫,需要建立DBAdapter類的一個執行個體:
public DBAdapter(Context ctx) { this.context = ctx; DBHelper = new DatabaseHelper(context); }
構造器中,同時建立了一個DBHelpter類去建立資料庫。
DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); }