Android 更新SQLite中的行,而不使用数据集中的所有信息

Android 更新SQLite中的行,而不使用数据集中的所有信息,android,android-sqlite,Android,Android Sqlite,我根据数据库中的信息创建一些对象。我的桌子看起来像这样: tbl_Book +-----+-------+---------+-------+------+ | _id | Title | Author | Pages | ISBN | +-----+-------+---------+-------+------+ | 1 | Test1 | Author1 | 111 | 1234 | | 2 | Test2 | Author2 | 222 | 2345 | | 3 |

我根据数据库中的信息创建一些对象。我的桌子看起来像这样:

tbl_Book
+-----+-------+---------+-------+------+
| _id | Title | Author  | Pages | ISBN |
+-----+-------+---------+-------+------+
|   1 | Test1 | Author1 |   111 | 1234 |
|   2 | Test2 | Author2 |   222 | 2345 |
|   3 | Test3 | Author  |   333 | 3456 |
+-----+-------+---------+-------+------+
我创建的对象只需要id、title和ISBN中的信息,所以我只从数据库中选择这些值来创建我的对象。现在我只想更新数据库中的ISBN,因此我的对象中有一个方法,代码如下:

Book b = new Book(id, title, isbn);
b.setISBN(value);

// Code from setISBN
public void setISBN(int isbn) 
{
    this.isbn= isbn;

    //  DB updaten
    ContentValues cv = new ContentValues();

    cv.put("_id", getId());
    cv.put("ISBN", isbn);

    db.replace("tbl_Book", null, cv);
}
但是使用此方法会产生
sqliteconstraintextException
,因为author、title和page都是空的。如果我只有数据集中的一些信息,如何更新表中的行?不应触摸数据集中的所有其他项目。

为什么不使用?似乎
\u id
是表的主键。如果您的目的只是在已经拥有主键的情况下更新记录,那么应该非常简单:

String whereClause = "_id=" + getId();
ContentValues cv = new ContentValues();
cv.put("ISBN", isbn);

//update(String table,ContentValue value, String whereClause, String[] whereArgs)
db.update("tbl_Book", cv, whereClause, null);
据我所知(可能我错了),将首先删除一行(如果它存在),然后根据提供的值插入一条新记录。在您的情况下,我认为它会删除相应的记录(基于id),然后尝试插入新记录:

例如,假设
\u id
为1:

+-----+-------+---------+-------+------+
| _id | Title | Author  | Pages | ISBN |
+-----+-------+---------+-------+------+
|   1 | Test1 | Author1 |   111 | 1234 |
将替换为:

+-----+-------+---------+-------+------+
| _id | Title | Author  | Pages | ISBN |
+-----+-------+---------+-------+------+
|   1 | NULL  |   NULL  |  NULL | 4321 |

我认为这不符合你的需要。因此,我认为
更新更适合您。

当然,您是对的。我不知道我为什么用替换。只是考虑不周。我认为你对replace()定义的想法是正确的。这是有道理的。回答得很好。非常感谢。