Android中對SQLite的操作

2021-08-30 03:02:59 字數 1628 閱讀 8243

1. 總論

通常自定義類,並繼承自sqliteopenhelper,在預設的建構函式中,會呼叫父類的建構函式。只需將資料庫名傳入即可。

super(context, database_name, null, database_version);
2. 建立表

首先,獲取乙個可寫的資料庫物件:

database = this.getwritabledatabase();
然後,呼叫execsql方法:

database.execsql("create table " + table_name + " (" 

+ id + " integer not null, "

+ title + " text not null, "

+ body + " text not null, "

+ date + " text not null, "

+ time + " text not null, "

+ people + " text not null " + ");"

);

3. 刪除表

同理,執行execsql方法:

database.execsql("drop table if exists " + table_name + ";");
4. 查詢記錄

核心**就一句:

cursor c = database.query(tablename, columns, whereclause, values,	null, null, null);
5. 插入記錄

需要用contentvalue來構造,其實就是乙個map。

contentvalues itemvalue = new contentvalues();

itemvalue.put(id, (integer) item.get(id));

itemvalue.put(title, (string) item.get(title));

itemvalue.put(body, (string) item.get(body));

itemvalue.put(date, (string) item.get(date));

itemvalue.put(time, (string) item.get(time));

itemvalue.put(people, (string) item.get(people));

database.insert(tablename, null, itemvalue);

6. 刪除記錄

rows = database.delete(tablename, this.getpeople() + "=?",new string );
返回影響的行數。

7. 通用操作

database.execsql( ... )
除查詢外的操作(如:create table, delete, insert)都可以在這裡進行,和hibernate裡面直接執行本地sql類似。

Android對SQLite批量新增資料

有人去面試的時候面試官問這麼乙個問題。如何將大量的資料同時插入到sqlite?或者說批量資料插入資料庫?本人總結了一下幾種方法,重點注意後面那一點 1.使用contentvalues插入 db.begintransaction 手動設定開始事務 for contentvalues v list db...

Android 中 SQLite 效能優化

sqlite效能的優化,在此記錄。乙個比較全面的sqlite資料庫講解 具體用法看上面的部落格。優點 加快了查操作 缺點 降低了增刪改操作的速度,增加了空間消耗,建立索引過程耗時。基於以上特點,具體情況判斷是否建立索引。sqlite想要執行操作,需要將程式中的sql語句編譯成對應的sqlitesta...

Android中SQLite操作示例

android中sqlite操作示例 在android中對sqlite資料庫的操作,涉及以下幾個方面 1 確認資料庫檔案,即.db檔案 2 通過android.database.sqlite.sqlitedatabase類的openorcreatedatabase 方法開啟資料庫 3 資料庫操作 a...