gpt4 book ai didi

android - 在没有数据集中的所有信息的情况下更新 SQLite 中的行

转载 作者:行者123 更新时间:2023-11-29 21:40:57 24 4
gpt4 key购买 nike

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

tbl_Book
+-----+-------+---------+-------+------+
| _id | Title | Author | Pages | ISBN |
+-----+-------+---------+-------+------+
| 1 | Test1 | Author1 | 111 | 1234 |
| 2 | Test2 | Author2 | 222 | 2345 |
| 3 | Test3 | Author | 333 | 3456 |
+-----+-------+---------+-------+------+

我创建的对象只需要来自id、标题和 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);
}

但使用此方法会导致 SQLiteConstraintException 因为 author、title 和 page 为空。如果我只有数据集中的一些信息,如何更新表中的一行?不应触及数据集中的所有其他项目。

最佳答案

为什么不使用 Update()_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);

据我所知(也许我错了),Replace()将首先删除一行(如果存在),然后根据提供的值插入一条新记录。我认为在你的情况下,它会删除相应的记录(基于 id),然后尝试插入新记录:

例如,假设 _id 是 1:

+-----+-------+---------+-------+------+
| _id | Title | Author | Pages | ISBN |
+-----+-------+---------+-------+------+
| 1 | Test1 | Author1 | 111 | 1234 |

将被替换为:

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

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

关于android - 在没有数据集中的所有信息的情况下更新 SQLite 中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17127551/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com