上次我向大家介紹了SQLite的基本信息和使用過程,相信朋友們對SQLite已經有所瞭解了,那今天呢,我就和大家分享一下在Android中如何使用SQLite。
現在的主流移動設備像Android、iPhone等都使用SQLite作爲複雜數據的存儲引擎,在我們爲移動設備開發應用程序時,也許就要使用到SQLite來存儲我們大量的數據,所以我們就需要掌握移動設備上的SQLite開發技巧。對於Android平臺來說,系統內置了豐富的API來供開發人員操作SQLite,我們可以輕鬆的完成對數據的存取。
下面就向大家介紹一下SQLite常用的操作方法,爲了方便,我將代碼寫在了Activity的onCreate中:
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- //打開或創建test.db數據庫
- SQLiteDatabase db = openOrCreateDatabase("test.db", Context.MODE_PRIVATE, null);
- db.execSQL("DROP TABLE IF EXISTS person");
- //創建person表
- db.execSQL("CREATE TABLE person (_id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, age SMALLINT)");
- Person person = new Person();
- person.name = "john";
- person.age = 30;
- //插入數據
- db.execSQL("INSERT INTO person VALUES (NULL, ?, ?)", new Object[]{person.name, person.age});
- person.name = "david";
- person.age = 33;
- //ContentValues以鍵值對的形式存放數據
- ContentValues cv = new ContentValues();
- cv.put("name", person.name);
- cv.put("age", person.age);
- //插入ContentValues中的數據
- db.insert("person", null, cv);
- cv = new ContentValues();
- cv.put("age", 35);
- //更新數據
- db.update("person", cv, "name = ?", new String[]{"john"});
- Cursor c = db.rawQuery("SELECT * FROM person WHERE age >= ?", new String[]{"33"});
- while (c.moveToNext()) {
- int _id = c.getInt(c.getColumnIndex("_id"));
- String name = c.getString(c.getColumnIndex("name"));
- int age = c.getInt(c.getColumnIndex("age"));
- Log.i("db", "_id=>" + _id + ", name=>" + name + ", age=>" + age);
- }
- c.close();
- //刪除數據
- db.delete("person", "age < ?", new String[]{"35"});
- //關閉當前數據庫
- db.close();
- //刪除test.db數據庫
- // deleteDatabase("test.db");
- }
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//打開或創建test.db數據庫
SQLiteDatabase db = openOrCreateDatabase("test.db", Context.MODE_PRIVATE, null);
db.execSQL("DROP TABLE IF EXISTS person");
//創建person表
db.execSQL("CREATE TABLE person (_id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, age SMALLINT)");
Person person = new Person();
person.name = "john";
person.age = 30;
//插入數據
db.execSQL("INSERT INTO person VALUES (NULL, ?, ?)", new Object[]{person.name, person.age});
person.name = "david";
person.age = 33;
//ContentValues以鍵值對的形式存放數據
ContentValues cv = new ContentValues();
cv.put("name", person.name);
cv.put("age", person.age);
//插入ContentValues中的數據
db.insert("person", null, cv);
cv = new ContentValues();
cv.put("age", 35);
//更新數據
db.update("person", cv, "name = ?", new String[]{"john"});
Cursor c = db.rawQuery("SELECT * FROM person WHERE age >= ?", new String[]{"33"});
while (c.moveToNext()) {
int _id = c.getInt(c.getColumnIndex("_id"));
String name = c.getString(c.getColumnIndex("name"));
int age = c.getInt(c.getColumnIndex("age"));
Log.i("db", "_id=>" + _id + ", name=>" + name + ", age=>" + age);
}
c.close();
//刪除數據
db.delete("person", "age < ?", new String[]{"35"});
//關閉當前數據庫
db.close();
//刪除test.db數據庫
// deleteDatabase("test.db");
}
在執行完上面的代碼後,系統就會在/data/data/[PACKAGE_NAME]/databases目錄下生成一個“test.db”的數據庫文件,如圖:
上面的代碼中基本上囊括了大部分的數據庫操作;對於添加、更新和刪除來說,我們都可以使用
- db.executeSQL(String sql);
- db.executeSQL(String sql, Object[] bindArgs);//sql語句中使用佔位符,然後第二個參數是實際的參數集
db.executeSQL(String sql);
db.executeSQL(String sql, Object[] bindArgs);//sql語句中使用佔位符,然後第二個參數是實際的參數集
除了統一的形式之外,他們還有各自的操作方法:
- db.insert(String table, String nullColumnHack, ContentValues values);
- db.update(String table, Contentvalues values, String whereClause, String whereArgs);
- db.delete(String table, String whereClause, String whereArgs);
db.insert(String table, String nullColumnHack, ContentValues values);
db.update(String table, Contentvalues values, String whereClause, String whereArgs);
db.delete(String table, String whereClause, String whereArgs);
以上三個方法的第一個參數都是表示要操作的表名;insert中的第二個參數表示如果插入的數據每一列都爲空的話,需要指定此行中某一列的名稱,系統將此列設置爲NULL,不至於出現錯誤;insert中的第三個參數是ContentValues類型的變量,是鍵值對組成的Map,key代表列名,value代表該列要插入的值;update的第二個參數也很類似,只不過它是更新該字段key爲最新的value值,第三個參數whereClause表示WHERE表達式,比如“age > ? and age
< ?”等,最後的whereArgs參數是佔位符的實際參數值;delete方法的參數也是一樣。
下面來說說查詢操作。查詢操作相對於上面的幾種操作要複雜些,因爲我們經常要面對着各種各樣的查詢條件,所以系統也考慮到這種複雜性,爲我們提供了較爲豐富的查詢形式:
- db.rawQuery(String sql, String[] selectionArgs);
- db.query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy);
- db.query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit);
- db.query(String distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit);
db.rawQuery(String sql, String[] selectionArgs);
db.query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy);
db.query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit);
db.query(String distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit);
上面幾種都是常用的查詢方法,第一種最爲簡單,將所有的SQL語句都組織到一個字符串中,使用佔位符代替實際參數,selectionArgs就是佔位符實際參數集;下面的幾種參數都很類似,columns表示要查詢的列所有名稱集,selection表示WHERE之後的條件語句,可以使用佔位符,groupBy指定分組的列名,having指定分組條件,配合groupBy使用,orderBy指定排序的列名,limit指定分頁參數,distinct可以指定“true”或“false”表示要不要過濾重複值。需要注意的是,selection、groupBy、having、orderBy、limit這幾個參數中不包括“WHERE”、“GROUP
BY”、“HAVING”、“ORDER BY”、“LIMIT”等SQL關鍵字。最後,他們同時返回一個Cursor對象,代表數據集的遊標,有點類似於JavaSE中的ResultSet。
下面是Cursor對象的常用方法:
- c.move(int offset); //以當前位置爲參考,移動到指定行
- c.moveToFirst(); //移動到第一行
- c.moveToLast(); //移動到最後一行
- c.moveToPosition(int position); //移動到指定行
- c.moveToPrevious(); //移動到前一行
- c.moveToNext(); //移動到下一行
- c.isFirst(); //是否指向第一條
- c.isLast(); //是否指向最後一條
- c.isBeforeFirst(); //是否指向第一條之前
- c.isAfterLast(); //是否指向最後一條之後
- c.isNull(int columnIndex); //指定列是否爲空(列基數爲0)
- c.isClosed(); //遊標是否已關閉
- c.getCount(); //總數據項數
- c.getPosition(); //返回當前遊標所指向的行數
- c.getColumnIndex(String columnName);//返回某列名對應的列索引值
- c.getString(int columnIndex); //返回當前行指定列的值
c.move(int offset); //以當前位置爲參考,移動到指定行
c.moveToFirst(); //移動到第一行
c.moveToLast(); //移動到最後一行
c.moveToPosition(int position); //移動到指定行
c.moveToPrevious(); //移動到前一行
c.moveToNext(); //移動到下一行
c.isFirst(); //是否指向第一條
c.isLast(); //是否指向最後一條
c.isBeforeFirst(); //是否指向第一條之前
c.isAfterLast(); //是否指向最後一條之後
c.isNull(int columnIndex); //指定列是否爲空(列基數爲0)
c.isClosed(); //遊標是否已關閉
c.getCount(); //總數據項數
c.getPosition(); //返回當前遊標所指向的行數
c.getColumnIndex(String columnName);//返回某列名對應的列索引值
c.getString(int columnIndex); //返回當前行指定列的值
在上面的代碼示例中,已經用到了這幾個常用方法中的一些,關於更多的信息,大家可以參考官方文檔中的說明。
最後當我們完成了對數據庫的操作後,記得調用SQLiteDatabase的close()方法釋放數據庫連接,否則容易出現SQLiteException。
上面就是SQLite的基本應用,但在實際開發中,爲了能夠更好的管理和維護數據庫,我們會封裝一個繼承自SQLiteOpenHelper類的數據庫操作類,然後以這個類爲基礎,再封裝我們的業務邏輯方法。
下面,我們就以一個實例來講解具體的用法,我們新建一個名爲db的項目,結構如下:
其中DBHelper繼承了SQLiteOpenHelper,作爲維護和管理數據庫的基類,DBManager是建立在DBHelper之上,封裝了常用的業務方法,Person是我們的person表對應的JavaBean,MainActivity就是我們顯示的界面。
下面我們先來看一下DBHelper:
- package com.scott.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會被調用
- @Override
- public void onCreate(SQLiteDatabase db) {
- db.execSQL("CREATE TABLE IF NOT EXISTS person" +
- "(_id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, age INTEGER, info TEXT)");
- }
- //如果DATABASE_VERSION值被改爲2,系統發現現有數據庫版本不同,即會調用onUpgrade
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
- db.execSQL("ALTER TABLE person ADD COLUMN other STRING");
- }
- }
package com.scott.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會被調用
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS person" +
"(_id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, age INTEGER, info TEXT)");
}
//如果DATABASE_VERSION值被改爲2,系統發現現有數據庫版本不同,即會調用onUpgrade
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("ALTER TABLE person ADD COLUMN other STRING");
}
}
正如上面所述,數據庫第一次創建時onCreate方法會被調用,我們可以執行創建表的語句,當系統發現版本變化之後,會調用onUpgrade方法,我們可以執行修改表結構等語句。
爲了方便我們面向對象的使用數據,我們建一個Person類,對應person表中的字段,如下:
- package com.scott.db;
- public class Person {
- public int _id;
- public String name;
- public int age;
- public String info;
- public Person() {
- }
- public Person(String name, int age, String info) {
- this.name = name;
- this.age = age;
- this.info = info;
- }
- }
package com.scott.db;
public class Person {
public int _id;
public String name;
public int age;
public String info;
public Person() {
}
public Person(String name, int age, String info) {
this.name = name;
this.age = age;
this.info = info;
}
}
然後,我們需要一個DBManager,來封裝我們所有的業務方法,代碼如下:
- package com.scott.db;
- import java.util.ArrayList;
- import java.util.List;
- import android.content.ContentValues;
- import android.content.Context;
- import android.database.Cursor;
- import android.database.sqlite.SQLiteDatabase;
- public class DBManager {
- private DBHelper helper;
- private SQLiteDatabase db;
- public DBManager(Context context) {
- helper = new DBHelper(context);
- //因爲getWritableDatabase內部調用了mContext.openOrCreateDatabase(mName, 0, mFactory);
- //所以要確保context已初始化,我們可以把實例化DBManager的步驟放在Activity的onCreate裏
- db = helper.getWritableDatabase();
- }
- /**
- * add persons
- * @param persons
- */
- public void add(List<Person> persons) {
- db.beginTransaction(); //開始事務
- try {
- for (Person person : persons) {
- db.execSQL("INSERT INTO person VALUES(null, ?, ?, ?)", new Object[]{person.name, person.age, person.info});
- }
- db.setTransactionSuccessful(); //設置事務成功完成
- } finally {
- db.endTransaction(); //結束事務
- }
- }
- /**
- * update person's age
- * @param person
- */
- public void updateAge(Person person) {
- ContentValues cv = new ContentValues();
- cv.put("age", person.age);
- db.update("person", cv, "name = ?", new String[]{person.name});
- }
- /**
- * delete old person
- * @param person
- */
- public void deleteOldPerson(Person person) {
- db.delete("person", "age >= ?", new String[]{String.valueOf(person.age)});
- }
- /**
- * query all persons, return list
- * @return List<Person>
- */
- public List<Person> query() {
- ArrayList<Person> persons = new ArrayList<Person>();
- Cursor c = queryTheCursor();
- while (c.moveToNext()) {
- Person person = new Person();
- person._id = c.getInt(c.getColumnIndex("_id"));
- person.name = c.getString(c.getColumnIndex("name"));
- person.age = c.getInt(c.getColumnIndex("age"));
- person.info = c.getString(c.getColumnIndex("info"));
- persons.add(person);
- }
- c.close();
- return persons;
- }
- /**
- * query all persons, return cursor
- * @return Cursor
- */
- public Cursor queryTheCursor() {
- Cursor c = db.rawQuery("SELECT * FROM person", null);
- return c;
- }
- /**
- * close database
- */
- public void closeDB() {
- db.close();
- }
- }
package com.scott.db;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class DBManager {
private DBHelper helper;
private SQLiteDatabase db;
public DBManager(Context context) {
helper = new DBHelper(context);
//因爲getWritableDatabase內部調用了mContext.openOrCreateDatabase(mName, 0, mFactory);
//所以要確保context已初始化,我們可以把實例化DBManager的步驟放在Activity的onCreate裏
db = helper.getWritableDatabase();
}
/**
* add persons
* @param persons
*/
public void add(List<Person> persons) {
db.beginTransaction(); //開始事務
try {
for (Person person : persons) {
db.execSQL("INSERT INTO person VALUES(null, ?, ?, ?)", new Object[]{person.name, person.age, person.info});
}
db.setTransactionSuccessful(); //設置事務成功完成
} finally {
db.endTransaction(); //結束事務
}
}
/**
* update person's age
* @param person
*/
public void updateAge(Person person) {
ContentValues cv = new ContentValues();
cv.put("age", person.age);
db.update("person", cv, "name = ?", new String[]{person.name});
}
/**
* delete old person
* @param person
*/
public void deleteOldPerson(Person person) {
db.delete("person", "age >= ?", new String[]{String.valueOf(person.age)});
}
/**
* query all persons, return list
* @return List<Person>
*/
public List<Person> query() {
ArrayList<Person> persons = new ArrayList<Person>();
Cursor c = queryTheCursor();
while (c.moveToNext()) {
Person person = new Person();
person._id = c.getInt(c.getColumnIndex("_id"));
person.name = c.getString(c.getColumnIndex("name"));
person.age = c.getInt(c.getColumnIndex("age"));
person.info = c.getString(c.getColumnIndex("info"));
persons.add(person);
}
c.close();
return persons;
}
/**
* query all persons, return cursor
* @return Cursor
*/
public Cursor queryTheCursor() {
Cursor c = db.rawQuery("SELECT * FROM person", null);
return c;
}
/**
* close database
*/
public void closeDB() {
db.close();
}
}
我們在DBManager構造方法中實例化DBHelper並獲取一個SQLiteDatabase對象,作爲整個應用的數據庫實例;在添加多個Person信息時,我們採用了事務處理,確保數據完整性;最後我們提供了一個closeDB方法,釋放數據庫資源,這一個步驟在我們整個應用關閉時執行,這個環節容易被忘記,所以朋友們要注意。
我們獲取數據庫實例時使用了getWritableDatabase()方法,也許朋友們會有疑問,在getWritableDatabase()和getReadableDatabase()中,你爲什麼選擇前者作爲整個應用的數據庫實例呢?在這裏我想和大家着重分析一下這一點。
我們來看一下SQLiteOpenHelper中的getReadableDatabase()方法:
- public synchronized SQLiteDatabase getReadableDatabase() {
- if (mDatabase != null && mDatabase.isOpen()) {
- // 如果發現mDatabase不爲空並且已經打開則直接返回
- return mDatabase;
- }
- if (mIsInitializing) {
- // 如果正在初始化則拋出異常
- throw new IllegalStateException("getReadableDatabase called recursively");
- }
- // 開始實例化數據庫mDatabase
- try {
- // 注意這裏是調用了getWritableDatabase()方法
- return getWritableDatabase();
- } catch (SQLiteException e) {
- if (mName == null)
- throw e; // Can't open a temp database read-only!
- Log.e(TAG, "Couldn't open " + mName + " for writing (will try read-only):", e);
- }
- // 如果無法以可讀寫模式打開數據庫 則以只讀方式打開
- SQLiteDatabase db = null;
- try {
- mIsInitializing = true;
- String path = mContext.getDatabasePath(mName).getPath();// 獲取數據庫路徑
- // 以只讀方式打開數據庫
- db = SQLiteDatabase.openDatabase(path, mFactory, SQLiteDatabase.OPEN_READONLY);
- if (db.getVersion() != mNewVersion) {
- throw new SQLiteException("Can't upgrade read-only database from version " + db.getVersion() + " to "
- + mNewVersion + ": " + path);
- }
- onOpen(db);
- Log.w(TAG, "Opened " + mName + " in read-only mode");
- mDatabase = db;// 爲mDatabase指定新打開的數據庫
- return mDatabase;// 返回打開的數據庫
- } finally {
- mIsInitializing = false;
- if (db != null && db != mDatabase)
- db.close();
- }
- }
public synchronized SQLiteDatabase getReadableDatabase() {
if (mDatabase != null && mDatabase.isOpen()) {
// 如果發現mDatabase不爲空並且已經打開則直接返回
return mDatabase;
}
if (mIsInitializing) {
// 如果正在初始化則拋出異常
throw new IllegalStateException("getReadableDatabase called recursively");
}
// 開始實例化數據庫mDatabase
try {
// 注意這裏是調用了getWritableDatabase()方法
return getWritableDatabase();
} catch (SQLiteException e) {
if (mName == null)
throw e; // Can't open a temp database read-only!
Log.e(TAG, "Couldn't open " + mName + " for writing (will try read-only):", e);
}
// 如果無法以可讀寫模式打開數據庫 則以只讀方式打開
SQLiteDatabase db = null;
try {
mIsInitializing = true;
String path = mContext.getDatabasePath(mName).getPath();// 獲取數據庫路徑
// 以只讀方式打開數據庫
db = SQLiteDatabase.openDatabase(path, mFactory, SQLiteDatabase.OPEN_READONLY);
if (db.getVersion() != mNewVersion) {
throw new SQLiteException("Can't upgrade read-only database from version " + db.getVersion() + " to "
+ mNewVersion + ": " + path);
}
onOpen(db);
Log.w(TAG, "Opened " + mName + " in read-only mode");
mDatabase = db;// 爲mDatabase指定新打開的數據庫
return mDatabase;// 返回打開的數據庫
} finally {
mIsInitializing = false;
if (db != null && db != mDatabase)
db.close();
}
}
在getReadableDatabase()方法中,首先判斷是否已存在數據庫實例並且是打開狀態,如果是,則直接返回該實例,否則試圖獲取一個可讀寫模式的數據庫實例,如果遇到磁盤空間已滿等情況獲取失敗的話,再以只讀模式打開數據庫,獲取數據庫實例並返回,然後爲mDatabase賦值爲最新打開的數據庫實例。既然有可能調用到getWritableDatabase()方法,我們就要看一下了:
- public synchronized SQLiteDatabase getWritableDatabase() {
- if (mDatabase != null && mDatabase.isOpen() && !mDatabase.isReadOnly()) {
- // 如果mDatabase不爲空已打開並且不是隻讀模式 則返回該實例
- return mDatabase;
- }
- if (mIsInitializing) {
- throw new IllegalStateException("getWritableDatabase called recursively");
- }
- // If we have a read-only database open, someone could be using it
- // (though they shouldn't), which would cause a lock to be held on
- // the file, and our attempts to open the database read-write would
- // fail waiting for the file lock. To prevent that, we acquire the
- // lock on the read-only database, which shuts out other users.
- boolean success = false;
- SQLiteDatabase db = null;
- // 如果mDatabase不爲空則加鎖 阻止其他的操作
- if (mDatabase != null)
- mDatabase.lock();
- try {
- mIsInitializing = true;
- if (mName == null) {
- db = SQLiteDatabase.create(null);
- } else {
- // 打開或創建數據庫
- db = mContext.openOrCreateDatabase(mName, 0, mFactory);
- }
- // 獲取數據庫版本(如果剛創建的數據庫,版本爲0)
- int version = db.getVersion();
- // 比較版本(我們代碼中的版本mNewVersion爲1)
- if (version != mNewVersion) {
- db.beginTransaction();// 開始事務
- try {
- if (version == 0) {
- // 執行我們的onCreate方法
- onCreate(db);
- } else {
- // 如果我們應用升級了mNewVersion爲2,而原版本爲1則執行onUpgrade方法
- onUpgrade(db, version, mNewVersion);
- }
- db.setVersion(mNewVersion);// 設置最新版本
- db.setTransactionSuccessful();// 設置事務成功
- } finally {
- db.endTransaction();// 結束事務
- }
- }
- onOpen(db);
- success = true;
- return db;// 返回可讀寫模式的數據庫實例
- } finally {
- mIsInitializing = false;
- if (success) {
- // 打開成功
- if (mDatabase != null) {
- // 如果mDatabase有值則先關閉
- try {
- mDatabase.close();
- } catch (Exception e) {
- }
- mDatabase.unlock();// 解鎖
- }
- mDatabase = db;// 賦值給mDatabase
- } else {
- // 打開失敗的情況:解鎖、關閉
- if (mDatabase != null)
- mDatabase.unlock();
- if (db != null)
- db.close();
- }
- }
- }
public synchronized SQLiteDatabase getWritableDatabase() {
if (mDatabase != null && mDatabase.isOpen() && !mDatabase.isReadOnly()) {
// 如果mDatabase不爲空已打開並且不是隻讀模式 則返回該實例
return mDatabase;
}
if (mIsInitializing) {
throw new IllegalStateException("getWritableDatabase called recursively");
}
// If we have a read-only database open, someone could be using it
// (though they shouldn't), which would cause a lock to be held on
// the file, and our attempts to open the database read-write would
// fail waiting for the file lock. To prevent that, we acquire the
// lock on the read-only database, which shuts out other users.
boolean success = false;
SQLiteDatabase db = null;
// 如果mDatabase不爲空則加鎖 阻止其他的操作
if (mDatabase != null)
mDatabase.lock();
try {
mIsInitializing = true;
if (mName == null) {
db = SQLiteDatabase.create(null);
} else {
// 打開或創建數據庫
db = mContext.openOrCreateDatabase(mName, 0, mFactory);
}
// 獲取數據庫版本(如果剛創建的數據庫,版本爲0)
int version = db.getVersion();
// 比較版本(我們代碼中的版本mNewVersion爲1)
if (version != mNewVersion) {
db.beginTransaction();// 開始事務
try {
if (version == 0) {
// 執行我們的onCreate方法
onCreate(db);
} else {
// 如果我們應用升級了mNewVersion爲2,而原版本爲1則執行onUpgrade方法
onUpgrade(db, version, mNewVersion);
}
db.setVersion(mNewVersion);// 設置最新版本
db.setTransactionSuccessful();// 設置事務成功
} finally {
db.endTransaction();// 結束事務
}
}
onOpen(db);
success = true;
return db;// 返回可讀寫模式的數據庫實例
} finally {
mIsInitializing = false;
if (success) {
// 打開成功
if (mDatabase != null) {
// 如果mDatabase有值則先關閉
try {
mDatabase.close();
} catch (Exception e) {
}
mDatabase.unlock();// 解鎖
}
mDatabase = db;// 賦值給mDatabase
} else {
// 打開失敗的情況:解鎖、關閉
if (mDatabase != null)
mDatabase.unlock();
if (db != null)
db.close();
}
}
}
大家可以看到,幾個關鍵步驟是,首先判斷mDatabase如果不爲空已打開並不是只讀模式則直接返回,否則如果mDatabase不爲空則加鎖,然後開始打開或創建數據庫,比較版本,根據版本號來調用相應的方法,爲數據庫設置新版本號,最後釋放舊的不爲空的mDatabase並解鎖,把新打開的數據庫實例賦予mDatabase,並返回最新實例。
看完上面的過程之後,大家或許就清楚了許多,如果不是在遇到磁盤空間已滿等情況,getReadableDatabase()一般都會返回和getWritableDatabase()一樣的數據庫實例,所以我們在DBManager構造方法中使用getWritableDatabase()獲取整個應用所使用的數據庫實例是可行的。當然如果你真的擔心這種情況會發生,那麼你可以先用getWritableDatabase()獲取數據實例,如果遇到異常,再試圖用getReadableDatabase()獲取實例,當然這個時候你獲取的實例只能讀不能寫了。
最後,讓我們看一下如何使用這些數據操作方法來顯示數據,下面是MainActivity.java的佈局文件和代碼:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- <Button
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="add"
- android:onClick="add"/>
- <Button
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="update"
- android:onClick="update"/>
- <Button
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="delete"
- android:onClick="delete"/>
- <Button
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="query"
- android:onClick="query"/>
- <Button
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="queryTheCursor"
- android:onClick="queryTheCursor"/>
- <ListView
- android:id="@+id/listView"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"/>
- </LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="add"
android:onClick="add"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="update"
android:onClick="update"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="delete"
android:onClick="delete"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="query"
android:onClick="query"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="queryTheCursor"
android:onClick="queryTheCursor"/>
<ListView
android:id="@+id/listView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
- package com.scott.db;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import android.app.Activity;
- import android.database.Cursor;
- import android.database.CursorWrapper;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.ListView;
- import android.widget.SimpleAdapter;
- import android.widget.SimpleCursorAdapter;
- public class MainActivity extends Activity {
- private DBManager mgr;
- private ListView listView;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- listView = (ListView) findViewById(R.id.listView);
- //初始化DBManager
- mgr = new DBManager(this);
- }
- @Override
- protected void onDestroy() {
- super.onDestroy();
- //應用的最後一個Activity關閉時應釋放DB
- mgr.closeDB();
- }
- public void add(View view) {
- ArrayList<Person> persons = new ArrayList<Person>();
- Person person1 = new Person("Ella", 22, "lively girl");
- Person person2 = new Person("Jenny", 22, "beautiful girl");
- Person person3 = new Person("Jessica", 23, "sexy girl");
- Person person4 = new Person("Kelly", 23, "hot baby");
- Person person5 = new Person("Jane", 25, "a pretty woman");
- persons.add(person1);
- persons.add(person2);
- persons.add(person3);
- persons.add(person4);
- persons.add(person5);
- mgr.add(persons);
- }
- public void update(View view) {
- Person person = new Person();
- person.name = "Jane";
- person.age = 30;
- mgr.updateAge(person);
- }
- public void delete(View view) {
- Person person = new Person();
- person.age = 30;
- mgr.deleteOldPerson(person);
- }
- public void query(View view) {
- List<Person> persons = mgr.query();
- ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();
- for (Person person : persons) {
- HashMap<String, String> map = new HashMap<String, String>();
- map.put("name", person.name);
- map.put("info", person.age + " years old, " + person.info);
- list.add(map);
- }
- SimpleAdapter adapter = new SimpleAdapter(this, list, android.R.layout.simple_list_item_2,
- new String[]{"name", "info"}, new int[]{android.R.id.text1, android.R.id.text2});
- listView.setAdapter(adapter);
- }
- public void queryTheCursor(View view) {
- Cursor c = mgr.queryTheCursor();
- startManagingCursor(c); //託付給activity根據自己的生命週期去管理Cursor的生命週期
- CursorWrapper cursorWrapper = new CursorWrapper(c) {
- @Override
- public String getString(int columnIndex) {
- //將簡介前加上年齡
- if (getColumnName(columnIndex).equals("info")) {
- int age = getInt(getColumnIndex("age"));
- return age + " years old, " + super.getString(columnIndex);
- }
- return super.getString(columnIndex);
- }
- };
- //確保查詢結果中有"_id"列
- SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2,
- cursorWrapper, new String[]{"name", "info"}, new int[]{android.R.id.text1, android.R.id.text2});
- ListView listView = (ListView) findViewById(R.id.listView);
- listView.setAdapter(adapter);
- }
- }
package com.scott.db;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.database.Cursor;
import android.database.CursorWrapper;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
public class MainActivity extends Activity {
private DBManager mgr;
private ListView listView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = (ListView) findViewById(R.id.listView);
//初始化DBManager
mgr = new DBManager(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
//應用的最後一個Activity關閉時應釋放DB
mgr.closeDB();
}
public void add(View view) {
ArrayList<Person> persons = new ArrayList<Person>();
Person person1 = new Person("Ella", 22, "lively girl");
Person person2 = new Person("Jenny", 22, "beautiful girl");
Person person3 = new Person("Jessica", 23, "sexy girl");
Person person4 = new Person("Kelly", 23, "hot baby");
Person person5 = new Person("Jane", 25, "a pretty woman");
persons.add(person1);
persons.add(person2);
persons.add(person3);
persons.add(person4);
persons.add(person5);
mgr.add(persons);
}
public void update(View view) {
Person person = new Person();
person.name = "Jane";
person.age = 30;
mgr.updateAge(person);
}
public void delete(View view) {
Person person = new Person();
person.age = 30;
mgr.deleteOldPerson(person);
}
public void query(View view) {
List<Person> persons = mgr.query();
ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();
for (Person person : persons) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", person.name);
map.put("info", person.age + " years old, " + person.info);
list.add(map);
}
SimpleAdapter adapter = new SimpleAdapter(this, list, android.R.layout.simple_list_item_2,
new String[]{"name", "info"}, new int[]{android.R.id.text1, android.R.id.text2});
listView.setAdapter(adapter);
}
public void queryTheCursor(View view) {
Cursor c = mgr.queryTheCursor();
startManagingCursor(c); //託付給activity根據自己的生命週期去管理Cursor的生命週期
CursorWrapper cursorWrapper = new CursorWrapper(c) {
@Override
public String getString(int columnIndex) {
//將簡介前加上年齡
if (getColumnName(columnIndex).equals("info")) {
int age = getInt(getColumnIndex("age"));
return age + " years old, " + super.getString(columnIndex);
}
return super.getString(columnIndex);
}
};
//確保查詢結果中有"_id"列
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2,
cursorWrapper, new String[]{"name", "info"}, new int[]{android.R.id.text1, android.R.id.text2});
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
}
}
這裏需要注意的是SimpleCursorAdapter的應用,當我們使用這個適配器時,我們必須先得到一個Cursor對象,這裏面有幾個問題:如何管理Cursor的生命週期,如果包裝Cursor,Cursor結果集都需要注意什麼。
如果手動去管理Cursor的話會非常的麻煩,還有一定的風險,處理不當的話運行期間就會出現異常,幸好Activity爲我們提供了startManagingCursor(Cursor cursor)方法,它會根據Activity的生命週期去管理當前的Cursor對象,下面是該方法的說明:
- /**
- * This method allows the activity to take care of managing the given
- * {@link Cursor}'s lifecycle for you based on the activity's lifecycle.
- * That is, when the activity is stopped it will automatically call
- * {@link Cursor#deactivate} on the given Cursor, and when it is later restarted
- * it will call {@link Cursor#requery} for you. When the activity is
- * destroyed, all managed Cursors will be closed automatically.
- *
- * @param c The Cursor to be managed.
- *
- * @see #managedQuery(android.net.Uri , String[], String, String[], String)
- * @see #stopManagingCursor
- */
/**
* This method allows the activity to take care of managing the given
* {@link Cursor}'s lifecycle for you based on the activity's lifecycle.
* That is, when the activity is stopped it will automatically call
* {@link Cursor#deactivate} on the given Cursor, and when it is later restarted
* it will call {@link Cursor#requery} for you. When the activity is
* destroyed, all managed Cursors will be closed automatically.
*
* @param c The Cursor to be managed.
*
* @see #managedQuery(android.net.Uri , String[], String, String[], String)
* @see #stopManagingCursor
*/
文中提到,startManagingCursor方法會根據Activity的生命週期去管理當前的Cursor對象的生命週期,就是說當Activity停止時他會自動調用Cursor的deactivate方法,禁用遊標,當Activity重新回到屏幕時它會調用Cursor的requery方法再次查詢,當Activity摧毀時,被管理的Cursor都會自動關閉釋放。
如何包裝Cursor:我們會使用到CursorWrapper對象去包裝我們的Cursor對象,實現我們需要的數據轉換工作,這個CursorWrapper實際上是實現了Cursor接口。我們查詢獲取到的Cursor其實是Cursor的引用,而系統實際返回給我們的必然是Cursor接口的一個實現類的對象實例,我們用CursorWrapper包裝這個實例,然後再使用SimpleCursorAdapter將結果顯示到列表上。
Cursor結果集需要注意些什麼:一個最需要注意的是,在我們的結果集中必須要包含一個“_id”的列,否則SimpleCursorAdapter就會翻臉不認人,爲什麼一定要這樣呢?因爲這源於SQLite的規範,主鍵以“_id”爲標準。解決辦法有三:第一,建表時根據規範去做;第二,查詢時用別名,例如:SELECT id AS _id FROM person;第三,在CursorWrapper裏做文章:
- CursorWrapper cursorWrapper = new CursorWrapper(c) {
- @Override
- public int getColumnIndexOrThrow(String columnName) throws IllegalArgumentException {
- if (columnName.equals("_id")) {
- return super.getColumnIndex("id");
- }
- return super.getColumnIndexOrThrow(columnName);
- }
- };
CursorWrapper cursorWrapper = new CursorWrapper(c) {
@Override
public int getColumnIndexOrThrow(String columnName) throws IllegalArgumentException {
if (columnName.equals("_id")) {
return super.getColumnIndex("id");
}
return super.getColumnIndexOrThrow(columnName);
}
};
如果試圖從CursorWrapper裏獲取“_id”對應的列索引,我們就返回查詢結果裏“id”對應的列索引即可。
最後我們來看一下結果如何: