gpt4 book ai didi

android - SQLite插入 “Column are not unique”崩溃

转载 作者:行者123 更新时间:2023-12-03 16:23:10 25 4
gpt4 key购买 nike

我试图避免数据库上的重复数据,所以我创建了UNIQUE列,并且通常可以向其中插入。

问题是,当我继续插入同一件事超过1次时,应用程序崩溃了。这是logcat:

07-03 10:33:53.577: ERROR/Database(19974): Failure 19 (columns SuraNumber, AyaNumber are not unique) on 0x2dc560 when executing 'INSERT INTO Favorite_Sura (SuraNumber,AyaNumber) VALUES (17,1)'
07-03 10:33:54.440: ERROR/AndroidRuntime(19974): FATAL EXCEPTION: Thread-11
07-03 10:33:54.440: ERROR/AndroidRuntime(19974): android.database.sqlite.SQLiteConstraintException: columns SuraNumber, AyaNumber are not unique: INSERT INTO Favorite_Sura (SuraNumber,AyaNumber) VALUES (17,1)
07-03 10:33:54.440: ERROR/AndroidRuntime(19974): at android.database.sqlite.SQLiteDatabase.native_execSQL(Native Method)
07-03 10:33:54.440: ERROR/AndroidRuntime(19974): at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1763)
07-03 10:33:54.440: ERROR/AndroidRuntime(19974): at omar.quran1.Quran$16.run(Quran.java:910)
07-03 10:33:54.440: ERROR/AndroidRuntime(19974): at java.lang.Thread.run(Thread.java:1019)

我用来插入的代码,SuraNumber和CurrentAya都是UNIQUE列:
     new Thread(new Runnable() {
public void run() {

/////////////// DATABASE
File dbfile = new File(Munawwat_Database_PATH);
if(!dbfile.exists())
{
Toast.makeText(mContext, "error in db location", Toast.LENGTH_SHORT);
}
GetStartPageAya();
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);
db.execSQL("INSERT INTO Favorite_Sura (SuraNumber,AyaNumber) VALUES ("+SuraNumber+","+CurrentAya+")");
db.close();
}}).start();

为什么会这样呢?谢谢。

UPDATE1:我用来创建表的sql:
CREATE TABLE Favorite_Sura
(
_Id INTEGER PRIMARY KEY,
SuraNumber int,
AyaNumber int,
UNIQUE (SuraNumber, AyaNumber)
)

最佳答案

您故意违反了UNIQUE约束吗?我不确定您认为会发生什么。如果您的应用程序可以忽略重复项,则捕获明显命名的SQLiteConstraintException;通常,UNIQUE字段是唯一的,这是有原因的,为保持应用程序逻辑一致性,必须为重复项引发异常。

关于android - SQLite插入 “Column are not unique”崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6561710/

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