简体   繁体   中英

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. 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. All comments are then linked to whatever other items you want to with a common key (the post_id column in the below example).

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.

(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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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