初學者在學android的時候,看到書上的sqlite資料庫編程怎麼有點複雜。
初學階段的痛點:
建立資料庫表欄位(field)資料類型(text,interge)選擇較多,考慮較多。
在activity中資料更新插入要考慮的約束條件好多
老是訪問資料庫的資料,每次都要在activity中聲明一個cursor並且通過一大堆代碼來擷取cursor感覺有點繁瑣。
對於上述的痛點解決方式如下
1.資料類型都用text(除了id編號)
2.在activity中無論插入或更新都只用DB檔案中同一個函數實現,並且不需要在activity中考慮任何因素(是否資料表中已經有當前要插入或更新的資料)
3.在DB檔案中 寫一個傳回值為cursor的函數(返回的cursor為常用的cursor)
要知道的一些原理
1) db.update(TABLE_NAME, cv, where, whereValues)如果更新資料失敗返回0
2)db.update(TABLE_NAME, cv, where, whereValues)更新表中符合 where=whereValue的所有值
3)假如要查詢的值或要更新的值有多個關鍵字約束,那麼可以安如下填寫where 跟where
String where = field1+"=? and " + field2 + "=? and " + field3 + "=?";String[] whereValues = {string1, string2, string3};//Cursor cursor = db.query(HSTRYBUYTABLE, null, where, whereValues, null, null, null);//db.update(HSTRYBUYTABLE, cv, where, whereValues);
4)return db.insert(HSTRYBUYTABLE, null, cv)只要調用就會在資料庫中插入資料
方案:
1)構建資料庫表時請預設“自動編號”,並且其他欄位資料類型都用text,(java中string類型容易轉換成其他資料類型)
public void onCreate(SQLiteDatabase db) {String sql = "create table "+YOUTABLENAME+" ("+TABLE_ID+" integer primary key autoincrement, "+TABLE_FIELD1+" text, "+TABLE_FIELD2+" text, "+TABLE_FIELD3+" text, "+TABLE_FIELD4+" text )";db.execSQL(sql);}
2)在HelpDB中寫個如下函數替代insrtDB 跟 updataDB,以後在其他地方直接拿來用就是了,別想那麼多,直接能用這個函數關鍵是update函數中的where語句寫的正確恰當(這裡的正確看工程需求)。
public int operateHProduct(String string1, String string2, Product string3){int i = 0;if(updateHProduct(string1, string2, string3) == 0 ){//嘗試更新資料i = 1;insertHProduct(string1, string2, string3);}return i;}