android中傻瓜式建立資料庫及高效資料庫作業碼的編寫

來源:互聯網
上載者:User

初學者在學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;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.