【发布时间】:2015-10-30 22:32:04
【问题描述】:
只是一个简单的 SQLite 问题...
我创建了一个这样的表:CREATE TABLE mytable (id INTEGER PRIMARY KEY AUTOINCREMENT, column1 TEXT, column2 TEXT, UNIQUE (column1, column2))
(我也试过用扩展名ON CONFLICT REPLACE)
但是如果我第二次使用相同的值调用我的插入方法,它们将被添加。例如
insert("one", "two");
insert("one", "two");
这样填充表格:
1 | one | two
2 | one | two
但在第二次调用后应该是这样的:
1 | one | two
这是我的插入函数:
public void insert(String a, String b){
ContentValues contentValues = new ContentValues();
contentValues.put("column1", a);
contentValues.put("column2", b);
try {
//database.insertWithOnConflict("mytable", null, contentValues, SQLiteDatabase.CONFLICT_IGNORE);
//database.insertWithOnConflict("mytable", null, contentValues, SQLiteDatabase.CONFLICT_REPLACE);
database.insertOrThrow("mytable", null, contentValues);
} catch (SQLiteConstraintException e) {
Log.e("insert", "SQLException: " + e.getLocalizedMessage());
}
}
编辑:
如果我打电话
insert("one", "two");
insert("three", "two");
表格应该这样填写:
1 | one | two
2 | three | two
【问题讨论】:
-
这与android几乎没有关系。您是否尝试在常规 sqlite 数据库上重现该问题?
-
您确定您的数据库实际上是这样声明的吗?可能是您使用了另一个定义,但没有重新创建表?
-
您可以发布选择查询吗?尝试将“_”添加到 id。我的意思是当你创建 tabala _id
-
我没有在常规的 sqlite db 上重现它......但是使用这个 create 语句重新创建了表,我卸载了应用程序。我使用内部的“_id”还是创建的“id”都没有关系。我选择了所有值来检查
Cursor cursor = database.query("mytable", new String[]{"column1", "column2"}, null, null, null, null, null, null);的正确插入 -
大多数情况下它与扩展“ON CONFLICT ROLLBACK”一起使用。但这很奇怪:如果我尝试插入很多行两次,第二次插入最后近二十个数据集时不会抛出约束异常,尽管必须有一个。有什么想法吗??
标签: android sqlite unique-constraint