簡體   English   中英

如何正確更新SQLite?

[英]How to correctly update SQLite?

我知道如何讀取寫入數據到android SQL數據庫,但是當我嘗試追加數據時遇到了一個問題。 當我這樣做時,它只會附加上一個記錄。

為了更新數據,我使用了`

ContentValues updateKoment = new ContentValues();
            updateKoment.put("comment", text.getText().toString());
             db.update("MyTab",updateKoment, "PhoneNr='"+newn+"'AND Name='"+contact+"'AND comment='"+previuscom+"' AND Answered='"+Yn+"'",null);

如果您能幫助我並指出正確的方向,那就太好了。

我相信您正在尋找的是insert android SQLiteDatabase

insert (String table, String nullColumnHack, ContentValues values)

也許您要在現有評論的末尾添加新評論? 在這種情況下,您可能應該重新設計數據庫,並在其中添加(即insert )任何新注釋到單獨的表中。 然后,所有注釋都將通過公共密鑰鏈接到您想要鏈接的其他任何項目(下例中的post_id列)。

例如,您可以在數據庫中設置此表:

Table Posts:
post_id  title  description
1        'Hey'  'Description'
2        'Ho'   'Another Description'


Table Comments:
comment_id  post_id  comment
1           1        'Nice Salute'
2           1        'Yeah really nice'
3           2        'Ho Ho Ho'

在您當前的代碼段中,最后一個注釋將始終替換任何現有注釋,也就是說,添加'Yeah really nice'注釋將替換'Nice salute'注釋。

(我不相信我在暗示我要提出的建議:)

您還可以從數據庫中讀取所有現有注釋,並將新注釋連接到結果:

String columns = { "comment" };
String constraint = "PhoneNr=? AND Name=? AND comment=? AND Answered=?";
String args[] = { newn, contact, previuscom, Yn };

Cursor cursor = db.query("MyTab", columns , constraint, args, null, null, null);
String comments = cursor.getString(cursor.getColumnIndex("comment"));
comments += text.getText().toString();

然后使用您的新注釋字符串更新同一行:

ContentValues updateKoment = new ContentValues();
updateKoment.put("comment", comments);
db.update("MyTab", updateKoment, constraint, args);

但是從我個人的觀點來看,這是一個非常棘手的解決方案,我內部的數據庫架構師會強烈勸阻您不要實施它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM