建立資料庫需要使用的api:sqliteopenhelper
* 必須定義乙個構造方法:
//arg1:資料庫的名字("people.db")
//arg2:游標工廠(通常直接傳人null,則系統會使用預設的工廠)
//arg3:資料庫版本號(從1開始),方便公升級使用,不斷設定更大的值會呼叫,onupgrade方法
public myopenhelper(context context, string name, curso***ctory factory, int version){}
* 資料庫被建立時會呼叫:oncreate方法
* 資料庫公升級時會呼叫:onupgrade方法
建立資料庫
//建立openhelper物件
myopenhelper oh = new myopenhelper(getcontext(), "person.db", null, 1);
//獲得資料庫物件,如果資料庫不存在,先建立資料庫,後獲得,如果存在,則直接獲得
sqlitedatabase db = oh.getwritabledatabase();
* getwritabledatabase():開啟可讀寫的資料庫
* getreadabledatabase():在磁碟空間不足時開啟唯讀資料庫,否則開啟可讀寫資料庫
* 在建立資料庫時建立表,id要用_id(系統自帶的都是這樣的,所以就入鄉隨俗),並且是自增長的,各欄位定義的型別是給程式設計師看的,告訴他們應該填入的資料型別,而實際中,傳入什麼型別到資料庫中都是以字元型別儲存的。但是當插入錯誤的資料型別時,插入的結果將不會按錯誤的儲存,改變為int型別的將會變為預設的0進行插入
public void oncreate(sqlitedatabase db)
資料庫的增刪改查,有兩種方式,第一種:sql語句,第二種:api方式
1.sql語句方式:
insert into person (name, phone, money) values ('張三', '159874611', 2000);
delete from person where name = '李四' and _id = 4;
update person set money = 6000 where name = '李四';
select name, phone from person where name = '張三';
2.使用api實現增刪改查//插入、刪除、更新,用execsql
db.execsql("insert into person (name, phone, money) values (?, ?, ?);", new object);
//查詢用rawquery
cursor cs = db.rawquery("select _id, name, money from person where name = ?;", new string);
3.事務//插入
//以鍵值對的形式儲存要存入資料庫的資料
contentvalues cv = new contentvalues();
cv.put("name", "劉能");
cv.put("phone", 1651646);
cv.put("money", 3500);
//返回值是該行的主鍵,如果出錯返回-1
long i = db.insert("person", null, cv);//第二個引數,是空字段的控制,一般直接使用null
// 刪除
//返回值是刪除的行數
int i = db.delete("person", "_id = ? and name = ?", new string);
// 修改
contentvalues cv = new contentvalues();
cv.put("money", 25000);
int i = db.update("person", cv, "name = ?", new string);
// 查詢
//arg1:要查詢的字段
//arg2:查詢條件
//arg3:填充查詢條件的佔位符
cursor cs = db.query("person", new string, "name = ?", new string, null, null, null);
while(cs.movetonext())
* 保證多條sql語句要麼同時成功,要麼同時失敗
* 最常見案例:銀行轉賬
* 事務api
try finally
資料庫操作 SQLite
sqlite 是乙個輕量級的關聯式資料庫。sqlite最初的設計目標是用於嵌入式系統,它占用資源非常少,在嵌入式裝置中,只需要幾百k的記憶體就夠了,目前應用於android ios windows phone等智慧型手機。ios 使用時sqlite,只需要加入 libsqlite3.dylib 依賴...
資料庫操作 SQLite
sqlite 是乙個輕量級的關聯式資料庫。sqlite最初的設計目標是用於嵌入式系統,它占用資源非常少,在嵌入式裝置中,只需要幾百k的記憶體就夠了,目前應用於android ios windows phone等智慧型手機。ios 使用時sqlite,只需要加入 libsqlite3.dylib 依賴...
SQLite資料庫操作
特點 輕量級 只用乙個動態的庫,是以單個檔案的形式進行訪問 跨平台 支援多個作業系統 零配置 無需安裝,直接使用 嵌入式 內嵌到手機中 3.在程式的內部可以通過資料庫的名稱訪問,其他應用不能訪問 4.路徑 data data 應用程式包名 database db 5.存放的型別 null 空值 in...