http://www.hiapk.com/bbs/thread-57703-1-1.html
使用Android
SDK內內建的SQLiteOpenHelper,可以方便的對SQLite資料庫進行操作,由於手機
平台所限,手機上的SQLite不能進行非常複雜的select,但是一般的增刪改查功能
也相當齊全,足夠滿足移動平台的使用。
首先,我們需要繼承SQLiteOpenHelper這個類,並覆蓋兩個抽象方法
public class
TestDatabase extends
SQLiteOpenHelper {
public
TestDatabase(Context context) {
// 建立一個名為test_db的資料庫
super
(context, "test_db"
, null
, 1);
}
@Override
public void
onCreate(SQLiteDatabase db) {
// 執行時,若表不存在,則建立之,注意SQLite資料庫中必須有一個_id的欄位作為主鍵,否則查詢時將報錯
String sql = "create table mytable (_id integer primary key autoincrement, stext text)"
;
db.execSQL(sql);
}
@Override
public void
onUpgrade(SQLiteDatabase db, int
oldVersion, int
newVersion) {
// 資料庫被改變時,將原先的表刪除
,然後建立新表
String sql = "drop table if exists mytable"
;
db.execSQL(sql);
onCreate(db);
}
}
隨後就是增刪改查的方法
public
Cursor select() {
SQLiteDatabase db = getReadableDatabase();
Cursor cur = db.query("mytable"
, null
, null
, null
, null
, null
, null
);
return
cur;
}
public long
insert(String text){
SQLiteDatabase db = getWritableDatabase();
ContentValues cv = new
ContentValues();
cv.put("stext"
, text);
long row = db.insert("mytable"
, null
, cv);
return
row;
}
public int
delete(int
id){
SQLiteDatabase db = getWritableDatabase();
String where = "_id=?"
;
String[] whereValue = {Integer.toString(id)};
return
db.delete("mytable"
, where, whereValue);
}
public int
update(int
id, String text){
SQLiteDatabase db = getWritableDatabase();
String where = "_id=?"
;
String[] whereValue = {Integer.toString(id)};
ContentValues cv = new
ContentValues();
cv.put("stext"
, text);
return
db.update("mytable"
, cv, where, whereValue);
}
其中db.query方法參數比較複雜,這裡全部置null是為了圖個省事,它的具體參數如下:
public
Cursor query (String table,String[]
columns, String selection, String[] selectionArgs, StringgroupBy, String
having, String orderBy)
table: 表名稱,不可為null
columns: 要返回的列名數組,置null表示返回所有列
selection: where子句,如果不需要where子句則置null,寫法如"_id=?",此處將要填的參數寫為?,供下方的selectionArgs填充
selectionArgs: where子句的所需值,該數組將依次填充selection中的每一個問號。
groupby: GroupBy子句
having: Having子句
orderBy: order by 子句
好了,操作SQLite就這麼簡單,當然與此同時,還要做一個介面用來顯示資料,本文就不再多言了