轉載請註明出處:http://blog.csdn.net/linglongxin24/article/details/53326323
本文出自【DylanAndroid的博客】
- 【玩轉SQLite系列】文章目錄
【玩轉SQLite系列】(五)SQLite數據庫優化
在平時的開發中,其實我們每次給數據庫中插入一條數據,數據庫都會單獨開啓一個事務,我們插入多少條數據,
就會對磁盤由多少次操作。這樣在數據比較多的情況下,大大的降低了數據庫的操作效率。那麼,針對這個問題,我們如何來進行優化呢?
1.先創建一個數據庫和創建一張表
/**
* 1.創建或打開數據庫連接
**/
private void openDataBase() {
File dataBaseFile = new File(Environment.getExternalStorageDirectory() + "/sqlite", Contacts.DATABASE_NAME3);
if (!dataBaseFile.getParentFile().exists()) {
dataBaseFile.mkdirs();
}
sqLiteDatabase = SQLiteDatabase.openOrCreateDatabase(dataBaseFile, null);
}
/****
* 2.創建表
*/
private void createTable() {
String sql = "CREATE TABLE " +
"IF NOT EXISTS " +
"user(" +
"id Integer PRIMARY KEY AUTOINCREMENT," +
"name varchar," +
"age Integer)";
sqLiteDatabase.execSQL(sql);
}
2.一般的插入數據,批量插入100條數據
我們用一般的數據庫插入操作去批量插入數據,然後記錄一下所耗費的時間。
/**
* 一般的插入數據,批量插入100條數據
*
* @param v
*/
public void general(View v) {
long startTime = System.currentTimeMillis();
String table = "user";
for (int i = 0; i < 100; i++) {
ContentValues contentValues = new ContentValues();
contentValues.put("name", "張三" + i);
contentValues.put("age", i);
sqLiteDatabase.insert(table, null, contentValues);
}
long endTime = System.currentTimeMillis();
String message = "總共耗時" + (endTime - startTime);
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
Log.d(Contacts.TAG, message);
}
3.優化後,批量插入100條數據
如何進行優化?
sqLiteDatabase.beginTransaction();開啓一個事務
sqLiteDatabase.setTransactionSuccessful();將數據庫事務設置爲成功
sqLiteDatabase.endTransaction();結束數據庫事務
上述三個方法在實際開發中經常聯合使用,我們開啓一個數據庫事務,並在批量操作數據庫後將數據庫事務設置爲成功,
最後調用結束事務的方法,在結束數據庫事務的時候,會先判斷數據庫事務的標誌是否是成功,默認失敗。如果成功,一次批量插入;
如果沒有設置成功,則數據庫事務進行回滾,對數據庫不產生影響。優化後的代碼
/**
* 優化後,批量插入100條數據
*
* @param v
*/
public void optimize(View v) {
long startTime = System.currentTimeMillis();
String table = "user";
/**開啓一個事務**/
sqLiteDatabase.beginTransaction();
try {
for (int i = 0; i < 100; i++) {
ContentValues contentValues = new ContentValues();
contentValues.put("name", "張三" + i);
contentValues.put("age", i);
sqLiteDatabase.insertOrThrow(table, null, contentValues);
}
/**將數據庫事務設置爲成功**/
sqLiteDatabase.setTransactionSuccessful();
} catch (Exception e) {
e.printStackTrace();
} finally {
/**結束數據庫事務**/
sqLiteDatabase.endTransaction();
}
long endTime = System.currentTimeMillis();
String message = "總共耗時" + (endTime - startTime);
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
Log.d(Contacts.TAG, message);
}
- 查看耗時
通過日誌我們可以看到,一般方法插入耗時1457ms;而優化後耗時68ms。快了將近21倍。