简体   繁体   English

如何正确更新SQLite?

[英]How to correctly update SQLite?

I know how to read write data to an android SQL database, but i ran over a problem when i am trying to append data. 我知道如何读取写入数据到android SQL数据库,但是当我尝试追加数据时遇到了一个问题。 When i do that it only appends Last record. 当我这样做时,它只会附加上一个记录。

For data update i am using ` 为了更新数据,我使用了`

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);

It would be nice if you could help me and point me in the right direction. 如果您能帮助我并指出正确的方向,那就太好了。

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

insert (String table, String nullColumnHack, ContentValues values)

Maybe you're trying to add a new comment to the end of any existing comments? 也许您要在现有评论的末尾添加新评论? If that is the case, you should probably re-design your database where you add (that is, insert ) any new comments to a separate table. 在这种情况下,您可能应该重新设计数据库,并在其中添加(即insert )任何新注释到单独的表中。 All comments are then linked to whatever other items you want to with a common key (the post_id column in the below example). 然后,所有注释都将通过公共密钥链接到您想要链接的其他任何项目(下例中的post_id列)。

You could for example have this table setup in your database: 例如,您可以在数据库中设置此表:

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'

As of your current code snippet the last comment will always replace any existing comments, that is, adding the 'Yeah really nice' comment would replace the 'Nice salute' comment. 在您当前的代码段中,最后一个注释将始终替换任何现有注释,也就是说,添加'Yeah really nice'注释将替换'Nice salute'注释。

(I don't believe I'm suggesting what I am about to suggest :) (我不相信我在暗示我要提出的建议:)

You could also read any existing comments from your database and concatenate the new comment to the result: 您还可以从数据库中读取所有现有注释,并将新注释连接到结果:

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();

And then update the same row with your new comments string: 然后使用您的新注释字符串更新同一行:

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

But as of my personal opinion this is a butt-ugly solution and the database architect within me would strongly discourage you implementing it. 但是从我个人的观点来看,这是一个非常棘手的解决方案,我内部的数据库架构师会强烈劝阻您不要实施它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM