Android編程之SQLite數(shù)據(jù)庫操作方法詳解
本文實例講述了Android SQLite數(shù)據(jù)庫操作方法。分享給大家供大家參考,具體如下:
SQLite and Android
SQLite簡介
SQLite是一個非常流行的嵌入式數(shù)據(jù)庫,它支持SQL語言,并且只利用很少的內存就有很好的性能。此外,它還是開源的,任何人都可以使用它。
SQLite由以下幾個組件組成:SQL編譯器、內核、后端以及附件。SQLite通過利用虛擬機和虛擬數(shù)據(jù)庫引擎(VDBE),使調試、修改和擴展SQLite的內核變得更加方便。
SQLite支持的數(shù)據(jù)類型包括:
1. TEXT (類似于Java的String)
2. INTEGER (類似于Java的long)
3. REAL (類似于Java的Double)
更多SQLite數(shù)據(jù)類型知識可以參考前面相關文章入:詳解SQLite中的數(shù)據(jù)類型
SQLite In Android
Android在運行時集成了SQLite,因此在Android中使用SQLite數(shù)據(jù)庫并不需要安裝過程和獲取數(shù)據(jù)庫使用權限,你只需要定義創(chuàng)建和更新數(shù)據(jù)庫的語句即可,其他的會由Android平臺替你搞定。
操作SQLite數(shù)據(jù)庫通常意味著操作文件系統(tǒng),這種操作還是比較耗時的,因此建議將數(shù)據(jù)庫操作異步執(zhí)行。
你的應用創(chuàng)建一個SQLite數(shù)據(jù)庫,數(shù)據(jù)在默認情況下,存儲在/DATA/data/APP_NAME/databases/FILENAME。這里DATA是Environment.getDataDirectory()方法返回的值,APP_NAME是你的應用包名
Android開發(fā)中使用SQLite數(shù)據(jù)庫
Activity可以使用Content Provider或者 Service訪問一個數(shù)據(jù)庫。
創(chuàng)建數(shù)據(jù)庫
Android不自動提供數(shù)據(jù)庫。在Android應用程序中使用SQLite,必須自己創(chuàng)建數(shù)據(jù)庫,然后創(chuàng)建表、索引、填充數(shù)據(jù)。Android提供了一個SQLiteOpenHelper幫助你創(chuàng)建一個數(shù)據(jù)庫,你只要繼承 SQLiteOpenHelper 類,就可以輕松的創(chuàng)建數(shù)據(jù)庫。
SQLiteOpenHelper 類根據(jù)開發(fā)應用程序的需要,封裝了創(chuàng)建和更新數(shù)據(jù)庫使用的邏輯。SQLiteOpenHelper 的子類,至少需要實現(xiàn)三個方法:
構造函數(shù),調用父類SQLiteOpenHelper的構造函數(shù)。這個方法需要四個參數(shù):上下文環(huán)境,數(shù)據(jù)庫名字,一個可選的游標工廠(通常是NULL),一個代表你正在使用的數(shù)據(jù)庫模型版本的整數(shù)。
onCreate()方法,它需要一個SQLiteDatabase對象作為參數(shù),根據(jù)需要對這個對象填充表和初始化數(shù)據(jù)。
onUpgrade()方法,它需要三個參數(shù),一個SQLiteDatabase對象,一個舊的版本號和一個新的版本號,這樣你就可以清楚如何把一個數(shù)據(jù)庫從舊的模型轉變?yōu)樾碌哪P汀?/p>
首先,定義需要創(chuàng)建的表結構,使用類來進行抽象,這里示例定義一個新浪微薄的帳號類:
public class AccountTable {
public static final String TABLE_NAME = "account_table";
public static final String UID = "uid";
public static final String USERNAME = "username";
public static final String USERNICK = "usernick";
public static final String AVATAR_URL = "avatar_url";
public static final String PORTRAIT = "portrait";
public static final String OAUTH_TOKEN = "oauth_token";
public static final String OAUTH_TOKEN_SECRET = "oauth_token_secret";
public static final String INFOJSON = "json";
}
下面代碼展示了如何繼承SQLiteOpenHelper創(chuàng)建數(shù)據(jù)庫,推薦使用單例類:
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import org.qii.weiciyuan.support.database.table.*;
class DatabaseHelper extends SQLiteOpenHelper {
private static DatabaseHelper singleton = null;
private static final String DATABASE_NAME = "weibo.db";
private static final int DATABASE_VERSION = 16;
static final String CREATE_ACCOUNT_TABLE_SQL = "create table " + AccountTable.TABLE_NAME
+ "("
+ AccountTable.UID + " integer primary key autoincrement,"
+ AccountTable.OAUTH_TOKEN + " text,"
+ AccountTable.OAUTH_TOKEN_SECRET + " text,"
+ AccountTable.PORTRAIT + " text,"
+ AccountTable.USERNAME + " text,"
+ AccountTable.USERNICK + " text,"
+ AccountTable.AVATAR_URL + " text,"
+ AccountTable.INFOJSON + " text"
+ ");";
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_ACCOUNT_TABLE_SQL);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch (oldVersion) {
default:
deleteAllTable(db);
onCreate(db);
}
}
public static synchronized DatabaseHelper getInstance() {
if (singleton == null) {
singleton = new DatabaseHelper(GlobalContext.getInstance());
}
return singleton;
}
private void deleteAllTable(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + AccountTable.TABLE_NAME);
}
}
增刪改查數(shù)據(jù)庫
因為SQLite支持標準的SQL語句,因此我們可以用標準SQL語句才增刪改查數(shù)據(jù)庫,推薦使用占位符的sql語句,看起來更加清爽,下面是我的代碼示例:
package com.hw.droid.hwcatalog;
public class DatabaseManager {
private static DatabaseManager singleton = null;
private SQLiteDatabase wsd = null;
private SQLiteDatabase rsd = null;
private DatabaseManager() {
}
public static DatabaseManager getInstance(Context context) {
if (singleton == null) {
synchronized (DatabaseManager.class) {
if (singleton == null) {
DatabaseHelper databaseHelper = DatabaseHelper.getInstance(context);
singleton = new DatabaseManager();
singleton.wsd = databaseHelper.getWritableDatabase();
singleton.rsd = databaseHelper.getReadableDatabase();
}
}
}
return singleton;
}
public void initAccountTable(List<AccountData> listDatas) {
if (listDatas == null || listDatas.size() <= 0) {
return;
}
wsd.beginTransaction();
try {
for (AccountData data : listDatas) {
insertAccountTable(data);
}
wsd.setTransactionSuccessful();
} finally {
wsd.endTransaction();
}
}
private void insertAccountTable(AccountData accData) {
String sql = "insert into " + AccountTable.TABLE_NAME + "(" + AccountTable.USERNAME + ", "
+ AccountTable.USERNICK + ", " + AccountTable.AVATAR_URL + ", " + AccountTable.PORTRAIT + ", "
+ AccountTable.OAUTH_TOKEN + ", " + AccountTable.OAUTH_TOKEN_SECRET + ", " + AccountTable.INFOJSON
+ " " + ")" + " values(?, ?, ?, ?, ?, ?, ?)";
wsd.execSQL(sql,
new Object[] { accData.getUserName(), accData.getUserNick(), accData.getUrl(), accData.getPort(),
accData.getToken(), accData.getSecret(), accData.getJson(), accData.getThreads(), });
}
public List<AccountData> getAccountDatas() {
List<AccountData> listDatas = selectAccountData();
return listDatas;
}
private List<AccountData> selectAccountData() {
List<AccountData> listAccountData = new ArrayList<AccountData>();
String querySql = "select " + AccountTable.USERNAME + ", " + AccountTable.USERNICK + ", " + AccountTable.AVATAR_URL + ", " + AccountTable.PORTRAIT + ", " + AccountTable.OAUTH_TOKEN + ", " + AccountTable.OAUTH_TOKEN_SECRET + ", " + AccountTable.INFOJSON " " + " from " + BbsForumsTable.TABLE_NAME;
Cursor cursor = rsd.rawQuery(querySql, null);
if (cursor.moveToFirst()) {
do {
AccountData data = new AccountData();
data.setUserName(cursor.getString(cursor.getColumnIndex(AccountTable.USERNAME)));
data.setUserNick(cursor.getString(cursor.getColumnIndex(AccountTable.USERNICK)));
data.setUrl(cursor.getString(cursor.getColumnIndex(AccountTable.AVATAR_URL)));
data.setPort(cursor.getString(cursor.getColumnIndex(AccountTable.PORTRAIT)));
data.setToken(cursor.getString(cursor.getColumnIndex(AccountTable.OAUTH_TOKEN)));
data.setSecret(cursor.getString(cursor.getColumnIndex(AccountTable.OAUTH_TOKEN_SECRET)));
data.setJson(cursor.getString(cursor.getColumnIndex(AccountTable.INFOJSON)));
listAccountData.add(data);
} while (cursor.moveToNext());
}
cursor.close();
return listAccountData;
}
public void deleteBbsDatas() {
String delSql = "delete from " + AccountTable.TABLE_NAME;
wsd.execSQL(delSql);
}
}
事物(DBTransaction)
Android中經常會用到數(shù)據(jù)庫緩存,特別是wifi情況下遇到數(shù)據(jù)不一致情況需要更新緩存數(shù)據(jù),這個時候就需要用到事物處理,保證操作的完整性和速度。Android中使用SQLite保證事務完整性示例如下:
public void initAccountTable(List<AccountData> listDatas) {
if (listDatas == null || listDatas.size() <= 0) {
return;
}
wsd.beginTransaction();
try {
for (AccountData data : listDatas) {
insertAccountTable(data);
}
wsd.setTransactionSuccessful();
} finally {
wsd.endTransaction();
}
}
通過beginTransaction()開啟事務,endTransaction()結束事務,并且設置事務執(zhí)行成功標識setTransactionSuccessful().
更多關于Android相關內容感興趣的讀者可查看本站專題:《Android操作SQLite數(shù)據(jù)庫技巧總結》、《Android數(shù)據(jù)庫操作技巧總結》、《Android編程之activity操作技巧總結》、《Android文件操作技巧匯總》、《Android開發(fā)入門與進階教程》、《Android資源操作技巧匯總》、《Android視圖View技巧總結》及《Android控件用法總結》
希望本文所述對大家Android程序設計有所幫助。
相關文章
關于Android WebView的loadData方法的注意事項分析
本篇文章是對Android中WebView的loadData方法的注意事項進行了詳細的分析介紹,需要的朋友參考下2013-06-06
Android App中實現(xiàn)簡單的刮刮卡抽獎效果的實例詳解
這篇文章主要介紹了Android App中實現(xiàn)簡單的刮刮卡抽獎效果的實例詳解,文中主要借助Bitmap的canvas.drawPath的api來實現(xiàn),需要的朋友可以參考下2016-03-03
簡介Android應用中sharedPreferences類存儲數(shù)據(jù)的用法
這篇文章主要介紹了Android應用中使用sharedPreferences類存儲數(shù)據(jù)的方法,文中舉了用SharedPreferences保存數(shù)據(jù)和讀取數(shù)據(jù)的例子,需要的朋友可以參考下2016-02-02
android中ViewPager結合Fragment進行無限滑動
本篇文章中主要介紹了android中ViewPager結合Fragment進行無限滑動,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-03-03

