Android sqlite應用詳解(轉自大牛SCOTT)

上次我向大家介紹了SQLite的基本信息和使用過程,相信朋友們對SQLite已經有所瞭解了,那今天呢,我就和大家分享一下在Android中如何使用SQLite。

現在的主流移動設備像Android、iPhone等都使用SQLite作爲複雜數據的存儲引擎,在我們爲移動設備開發應用程序時,也許就要使用到SQLite來存儲我們大量的數據,所以我們就需要掌握移動設備上的SQLite開發技巧。對於Android平臺來說,系統內置了豐富的API來供開發人員操作SQLite,我們可以輕鬆的完成對數據的存取。

下面就向大家介紹一下SQLite常用的操作方法,爲了方便,我將代碼寫在了Activity的onCreate中:

  1.     @Override  
  2.     protected void onCreate(Bundle savedInstanceState) {  
  3.         super.onCreate(savedInstanceState);  
  4.           
  5.         //打開或創建test.db數據庫   
  6.         SQLiteDatabase db = openOrCreateDatabase("test.db", Context.MODE_PRIVATE, null);  
  7.         db.execSQL("DROP TABLE IF EXISTS person");  
  8.         //創建person表   
  9.         db.execSQL("CREATE TABLE person (_id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, age SMALLINT)");  
  10.         Person person = new Person();  
  11.         person.name = "john";  
  12.         person.age = 30;  
  13.         //插入數據   
  14.         db.execSQL("INSERT INTO person VALUES (NULL, ?, ?)"new Object[]{person.name, person.age});  
  15.           
  16.         person.name = "david";  
  17.         person.age = 33;  
  18.         //ContentValues以鍵值對的形式存放數據   
  19.         ContentValues cv = new ContentValues();  
  20.         cv.put("name", person.name);  
  21.         cv.put("age", person.age);  
  22.         //插入ContentValues中的數據   
  23.         db.insert("person"null, cv);  
  24.           
  25.         cv = new ContentValues();  
  26.         cv.put("age"35);  
  27.         //更新數據   
  28.         db.update("person", cv, "name = ?"new String[]{"john"});  
  29.           
  30.         Cursor c = db.rawQuery("SELECT * FROM person WHERE age >= ?"new String[]{"33"});  
  31.         while (c.moveToNext()) {  
  32.             int _id = c.getInt(c.getColumnIndex("_id"));  
  33.             String name = c.getString(c.getColumnIndex("name"));  
  34.             int age = c.getInt(c.getColumnIndex("age"));  
  35.             Log.i("db""_id=>" + _id + ", name=>" + name + ", age=>" + age);  
  36.         }  
  37.         c.close();  
  38.           
  39.         //刪除數據   
  40.         db.delete("person""age < ?"new String[]{"35"});  
  41.           
  42.         //關閉當前數據庫   
  43.         db.close();  
  44.           
  45.         //刪除test.db數據庫   
  46. //      deleteDatabase("test.db");   
  47.     }  
	@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”的數據庫文件,如圖:


上面的代碼中基本上囊括了大部分的數據庫操作;對於添加、更新和刪除來說,我們都可以使用

  1. db.executeSQL(String sql);  
  2. db.executeSQL(String sql, Object[] bindArgs);//sql語句中使用佔位符,然後第二個參數是實際的參數集  
db.executeSQL(String sql);
db.executeSQL(String sql, Object[] bindArgs);//sql語句中使用佔位符,然後第二個參數是實際的參數集
除了統一的形式之外,他們還有各自的操作方法:

  1. db.insert(String table, String nullColumnHack, ContentValues values);  
  2. db.update(String table, Contentvalues values, String whereClause, String whereArgs);  
  3. 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方法的參數也是一樣。

下面來說說查詢操作。查詢操作相對於上面的幾種操作要複雜些,因爲我們經常要面對着各種各樣的查詢條件,所以系統也考慮到這種複雜性,爲我們提供了較爲豐富的查詢形式:

  1. db.rawQuery(String sql, String[] selectionArgs);  
  2. db.query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy);  
  3. db.query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit);  
  4. 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對象的常用方法:

  1. c.move(int offset); //以當前位置爲參考,移動到指定行   
  2. c.moveToFirst();    //移動到第一行   
  3. c.moveToLast();     //移動到最後一行   
  4. c.moveToPosition(int position); //移動到指定行   
  5. c.moveToPrevious(); //移動到前一行   
  6. c.moveToNext();     //移動到下一行   
  7. c.isFirst();        //是否指向第一條   
  8. c.isLast();     //是否指向最後一條   
  9. c.isBeforeFirst();  //是否指向第一條之前   
  10. c.isAfterLast();    //是否指向最後一條之後   
  11. c.isNull(int columnIndex);  //指定列是否爲空(列基數爲0)   
  12. c.isClosed();       //遊標是否已關閉   
  13. c.getCount();       //總數據項數   
  14. c.getPosition();    //返回當前遊標所指向的行數   
  15. c.getColumnIndex(String columnName);//返回某列名對應的列索引值   
  16. 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:

  1. package com.scott.db;  
  2.   
  3. import android.content.Context;  
  4. import android.database.sqlite.SQLiteDatabase;  
  5. import android.database.sqlite.SQLiteOpenHelper;  
  6.   
  7. public class DBHelper extends SQLiteOpenHelper {  
  8.   
  9.     private static final String DATABASE_NAME = "test.db";  
  10.     private static final int DATABASE_VERSION = 1;  
  11.       
  12.     public DBHelper(Context context) {  
  13.         //CursorFactory設置爲null,使用默認值   
  14.         super(context, DATABASE_NAME, null, DATABASE_VERSION);  
  15.     }  
  16.   
  17.     //數據庫第一次被創建時onCreate會被調用   
  18.     @Override  
  19.     public void onCreate(SQLiteDatabase db) {  
  20.         db.execSQL("CREATE TABLE IF NOT EXISTS person" +  
  21.                 "(_id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, age INTEGER, info TEXT)");  
  22.     }  
  23.   
  24.     //如果DATABASE_VERSION值被改爲2,系統發現現有數據庫版本不同,即會調用onUpgrade   
  25.     @Override  
  26.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  27.         db.execSQL("ALTER TABLE person ADD COLUMN other STRING");  
  28.     }  
  29. }  
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表中的字段,如下:

  1. package com.scott.db;  
  2.   
  3. public class Person {  
  4.     public int _id;  
  5.     public String name;  
  6.     public int age;  
  7.     public String info;  
  8.       
  9.     public Person() {  
  10.     }  
  11.       
  12.     public Person(String name, int age, String info) {  
  13.         this.name = name;  
  14.         this.age = age;  
  15.         this.info = info;  
  16.     }  
  17. }  
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,來封裝我們所有的業務方法,代碼如下:

  1. package com.scott.db;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import android.content.ContentValues;  
  7. import android.content.Context;  
  8. import android.database.Cursor;  
  9. import android.database.sqlite.SQLiteDatabase;  
  10.   
  11. public class DBManager {  
  12.     private DBHelper helper;  
  13.     private SQLiteDatabase db;  
  14.       
  15.     public DBManager(Context context) {  
  16.         helper = new DBHelper(context);  
  17.         //因爲getWritableDatabase內部調用了mContext.openOrCreateDatabase(mName, 0, mFactory);   
  18.         //所以要確保context已初始化,我們可以把實例化DBManager的步驟放在Activity的onCreate裏   
  19.         db = helper.getWritableDatabase();  
  20.     }  
  21.       
  22.     /** 
  23.      * add persons 
  24.      * @param persons 
  25.      */  
  26.     public void add(List<Person> persons) {  
  27.         db.beginTransaction();  //開始事務   
  28.         try {  
  29.             for (Person person : persons) {  
  30.                 db.execSQL("INSERT INTO person VALUES(null, ?, ?, ?)"new Object[]{person.name, person.age, person.info});  
  31.             }  
  32.             db.setTransactionSuccessful();  //設置事務成功完成   
  33.         } finally {  
  34.             db.endTransaction();    //結束事務   
  35.         }  
  36.     }  
  37.       
  38.     /** 
  39.      * update person's age 
  40.      * @param person 
  41.      */  
  42.     public void updateAge(Person person) {  
  43.         ContentValues cv = new ContentValues();  
  44.         cv.put("age", person.age);  
  45.         db.update("person", cv, "name = ?"new String[]{person.name});  
  46.     }  
  47.       
  48.     /** 
  49.      * delete old person 
  50.      * @param person 
  51.      */  
  52.     public void deleteOldPerson(Person person) {  
  53.         db.delete("person""age >= ?"new String[]{String.valueOf(person.age)});  
  54.     }  
  55.       
  56.     /** 
  57.      * query all persons, return list 
  58.      * @return List<Person> 
  59.      */  
  60.     public List<Person> query() {  
  61.         ArrayList<Person> persons = new ArrayList<Person>();  
  62.         Cursor c = queryTheCursor();  
  63.         while (c.moveToNext()) {  
  64.             Person person = new Person();  
  65.             person._id = c.getInt(c.getColumnIndex("_id"));  
  66.             person.name = c.getString(c.getColumnIndex("name"));  
  67.             person.age = c.getInt(c.getColumnIndex("age"));  
  68.             person.info = c.getString(c.getColumnIndex("info"));  
  69.             persons.add(person);  
  70.         }  
  71.         c.close();  
  72.         return persons;  
  73.     }  
  74.       
  75.     /** 
  76.      * query all persons, return cursor 
  77.      * @return  Cursor 
  78.      */  
  79.     public Cursor queryTheCursor() {  
  80.         Cursor c = db.rawQuery("SELECT * FROM person"null);  
  81.         return c;  
  82.     }  
  83.       
  84.     /** 
  85.      * close database 
  86.      */  
  87.     public void closeDB() {  
  88.         db.close();  
  89.     }  
  90. }  
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()方法:

  1. public synchronized SQLiteDatabase getReadableDatabase() {  
  2.     if (mDatabase != null && mDatabase.isOpen()) {  
  3.         // 如果發現mDatabase不爲空並且已經打開則直接返回   
  4.         return mDatabase;  
  5.     }  
  6.   
  7.     if (mIsInitializing) {  
  8.         // 如果正在初始化則拋出異常   
  9.         throw new IllegalStateException("getReadableDatabase called recursively");  
  10.     }  
  11.   
  12.     // 開始實例化數據庫mDatabase   
  13.   
  14.     try {  
  15.         // 注意這裏是調用了getWritableDatabase()方法   
  16.         return getWritableDatabase();  
  17.     } catch (SQLiteException e) {  
  18.         if (mName == null)  
  19.             throw e; // Can't open a temp database read-only!   
  20.         Log.e(TAG, "Couldn't open " + mName + " for writing (will try read-only):", e);  
  21.     }  
  22.   
  23.     // 如果無法以可讀寫模式打開數據庫 則以只讀方式打開   
  24.   
  25.     SQLiteDatabase db = null;  
  26.     try {  
  27.         mIsInitializing = true;  
  28.         String path = mContext.getDatabasePath(mName).getPath();// 獲取數據庫路徑   
  29.         // 以只讀方式打開數據庫   
  30.         db = SQLiteDatabase.openDatabase(path, mFactory, SQLiteDatabase.OPEN_READONLY);  
  31.         if (db.getVersion() != mNewVersion) {  
  32.             throw new SQLiteException("Can't upgrade read-only database from version " + db.getVersion() + " to "  
  33.                     + mNewVersion + ": " + path);  
  34.         }  
  35.   
  36.         onOpen(db);  
  37.         Log.w(TAG, "Opened " + mName + " in read-only mode");  
  38.         mDatabase = db;// 爲mDatabase指定新打開的數據庫   
  39.         return mDatabase;// 返回打開的數據庫   
  40.     } finally {  
  41.         mIsInitializing = false;  
  42.         if (db != null && db != mDatabase)  
  43.             db.close();  
  44.     }  
  45. }  
	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()方法,我們就要看一下了:

  1. public synchronized SQLiteDatabase getWritableDatabase() {  
  2.     if (mDatabase != null && mDatabase.isOpen() && !mDatabase.isReadOnly()) {  
  3.         // 如果mDatabase不爲空已打開並且不是隻讀模式 則返回該實例   
  4.         return mDatabase;  
  5.     }  
  6.   
  7.     if (mIsInitializing) {  
  8.         throw new IllegalStateException("getWritableDatabase called recursively");  
  9.     }  
  10.   
  11.     // If we have a read-only database open, someone could be using it   
  12.     // (though they shouldn't), which would cause a lock to be held on   
  13.     // the file, and our attempts to open the database read-write would   
  14.     // fail waiting for the file lock. To prevent that, we acquire the   
  15.     // lock on the read-only database, which shuts out other users.   
  16.   
  17.     boolean success = false;  
  18.     SQLiteDatabase db = null;  
  19.     // 如果mDatabase不爲空則加鎖 阻止其他的操作   
  20.     if (mDatabase != null)  
  21.         mDatabase.lock();  
  22.     try {  
  23.         mIsInitializing = true;  
  24.         if (mName == null) {  
  25.             db = SQLiteDatabase.create(null);  
  26.         } else {  
  27.             // 打開或創建數據庫   
  28.             db = mContext.openOrCreateDatabase(mName, 0, mFactory);  
  29.         }  
  30.         // 獲取數據庫版本(如果剛創建的數據庫,版本爲0)   
  31.         int version = db.getVersion();  
  32.         // 比較版本(我們代碼中的版本mNewVersion爲1)   
  33.         if (version != mNewVersion) {  
  34.             db.beginTransaction();// 開始事務   
  35.             try {  
  36.                 if (version == 0) {  
  37.                     // 執行我們的onCreate方法   
  38.                     onCreate(db);  
  39.                 } else {  
  40.                     // 如果我們應用升級了mNewVersion爲2,而原版本爲1則執行onUpgrade方法   
  41.                     onUpgrade(db, version, mNewVersion);  
  42.                 }  
  43.                 db.setVersion(mNewVersion);// 設置最新版本   
  44.                 db.setTransactionSuccessful();// 設置事務成功   
  45.             } finally {  
  46.                 db.endTransaction();// 結束事務   
  47.             }  
  48.         }  
  49.   
  50.         onOpen(db);  
  51.         success = true;  
  52.         return db;// 返回可讀寫模式的數據庫實例   
  53.     } finally {  
  54.         mIsInitializing = false;  
  55.         if (success) {  
  56.             // 打開成功   
  57.             if (mDatabase != null) {  
  58.                 // 如果mDatabase有值則先關閉   
  59.                 try {  
  60.                     mDatabase.close();  
  61.                 } catch (Exception e) {  
  62.                 }  
  63.                 mDatabase.unlock();// 解鎖   
  64.             }  
  65.             mDatabase = db;// 賦值給mDatabase   
  66.         } else {  
  67.             // 打開失敗的情況:解鎖、關閉   
  68.             if (mDatabase != null)  
  69.                 mDatabase.unlock();  
  70.             if (db != null)  
  71.                 db.close();  
  72.         }  
  73.     }  
  74. }  
	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的佈局文件和代碼:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent">  
  6.     <Button  
  7.         android:layout_width="fill_parent"  
  8.         android:layout_height="wrap_content"  
  9.         android:text="add"  
  10.         android:onClick="add"/>  
  11.     <Button  
  12.         android:layout_width="fill_parent"  
  13.         android:layout_height="wrap_content"  
  14.         android:text="update"  
  15.         android:onClick="update"/>  
  16.     <Button  
  17.         android:layout_width="fill_parent"  
  18.         android:layout_height="wrap_content"  
  19.         android:text="delete"  
  20.         android:onClick="delete"/>  
  21.     <Button  
  22.         android:layout_width="fill_parent"  
  23.         android:layout_height="wrap_content"  
  24.         android:text="query"  
  25.         android:onClick="query"/>  
  26.     <Button  
  27.         android:layout_width="fill_parent"  
  28.         android:layout_height="wrap_content"  
  29.         android:text="queryTheCursor"  
  30.         android:onClick="queryTheCursor"/>  
  31.     <ListView  
  32.         android:id="@+id/listView"  
  33.         android:layout_width="fill_parent"  
  34.         android:layout_height="wrap_content"/>  
  35. </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>

  1. package com.scott.db;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.HashMap;  
  5. import java.util.List;  
  6. import java.util.Map;  
  7.   
  8. import android.app.Activity;  
  9. import android.database.Cursor;  
  10. import android.database.CursorWrapper;  
  11. import android.os.Bundle;  
  12. import android.view.View;  
  13. import android.widget.ListView;  
  14. import android.widget.SimpleAdapter;  
  15. import android.widget.SimpleCursorAdapter;  
  16.   
  17.   
  18. public class MainActivity extends Activity {  
  19.      
  20.     private DBManager mgr;  
  21.     private ListView listView;  
  22.       
  23.     @Override  
  24.     public void onCreate(Bundle savedInstanceState) {  
  25.         super.onCreate(savedInstanceState);  
  26.         setContentView(R.layout.main);  
  27.         listView = (ListView) findViewById(R.id.listView);  
  28.         //初始化DBManager   
  29.         mgr = new DBManager(this);  
  30.     }  
  31.       
  32.     @Override  
  33.     protected void onDestroy() {  
  34.         super.onDestroy();  
  35.         //應用的最後一個Activity關閉時應釋放DB   
  36.         mgr.closeDB();  
  37.     }  
  38.       
  39.     public void add(View view) {  
  40.         ArrayList<Person> persons = new ArrayList<Person>();  
  41.           
  42.         Person person1 = new Person("Ella"22"lively girl");  
  43.         Person person2 = new Person("Jenny"22"beautiful girl");  
  44.         Person person3 = new Person("Jessica"23"sexy girl");  
  45.         Person person4 = new Person("Kelly"23"hot baby");  
  46.         Person person5 = new Person("Jane"25"a pretty woman");  
  47.           
  48.         persons.add(person1);  
  49.         persons.add(person2);  
  50.         persons.add(person3);  
  51.         persons.add(person4);  
  52.         persons.add(person5);  
  53.           
  54.         mgr.add(persons);  
  55.     }  
  56.       
  57.     public void update(View view) {  
  58.         Person person = new Person();  
  59.         person.name = "Jane";  
  60.         person.age = 30;  
  61.         mgr.updateAge(person);  
  62.     }  
  63.       
  64.     public void delete(View view) {  
  65.         Person person = new Person();  
  66.         person.age = 30;  
  67.         mgr.deleteOldPerson(person);  
  68.     }  
  69.       
  70.     public void query(View view) {  
  71.         List<Person> persons = mgr.query();  
  72.         ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();  
  73.         for (Person person : persons) {  
  74.             HashMap<String, String> map = new HashMap<String, String>();  
  75.             map.put("name", person.name);  
  76.             map.put("info", person.age + " years old, " + person.info);  
  77.             list.add(map);  
  78.         }  
  79.         SimpleAdapter adapter = new SimpleAdapter(this, list, android.R.layout.simple_list_item_2,  
  80.                     new String[]{"name""info"}, new int[]{android.R.id.text1, android.R.id.text2});  
  81.         listView.setAdapter(adapter);  
  82.     }  
  83.       
  84.     public void queryTheCursor(View view) {  
  85.         Cursor c = mgr.queryTheCursor();  
  86.         startManagingCursor(c); //託付給activity根據自己的生命週期去管理Cursor的生命週期   
  87.         CursorWrapper cursorWrapper = new CursorWrapper(c) {  
  88.             @Override  
  89.             public String getString(int columnIndex) {  
  90.                 //將簡介前加上年齡   
  91.                 if (getColumnName(columnIndex).equals("info")) {  
  92.                     int age = getInt(getColumnIndex("age"));  
  93.                     return age + " years old, " + super.getString(columnIndex);  
  94.                 }  
  95.                 return super.getString(columnIndex);  
  96.             }  
  97.         };  
  98.         //確保查詢結果中有"_id"列   
  99.         SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2,   
  100.                 cursorWrapper, new String[]{"name""info"}, new int[]{android.R.id.text1, android.R.id.text2});  
  101.         ListView listView = (ListView) findViewById(R.id.listView);  
  102.         listView.setAdapter(adapter);  
  103.     }  
  104. }  
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對象,下面是該方法的說明:

  1. /** 
  2.      * This method allows the activity to take care of managing the given 
  3.      * {@link Cursor}'s lifecycle for you based on the activity's lifecycle. 
  4.      * That is, when the activity is stopped it will automatically call 
  5.      * {@link Cursor#deactivate} on the given Cursor, and when it is later restarted 
  6.      * it will call {@link Cursor#requery} for you.  When the activity is 
  7.      * destroyed, all managed Cursors will be closed automatically. 
  8.      *  
  9.      * @param c The Cursor to be managed. 
  10.      *  
  11.      * @see #managedQuery(android.net.Uri , String[], String, String[], String) 
  12.      * @see #stopManagingCursor 
  13.      */  
/**
     * 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裏做文章:

  1. CursorWrapper cursorWrapper = new CursorWrapper(c) {  
  2.     @Override  
  3.     public int getColumnIndexOrThrow(String columnName) throws IllegalArgumentException {  
  4.         if (columnName.equals("_id")) {  
  5.             return super.getColumnIndex("id");  
  6.         }  
  7.         return super.getColumnIndexOrThrow(columnName);  
  8.     }  
  9. };  
    	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”對應的列索引即可。

最後我們來看一下結果如何:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章