我尝试将数据保存到MyList,但出现此错误:UNIQUE约束失败。我的错在哪里?
我的数据库
db.execSQL("CREATE TABLE IF NOT EXISTS \"Words\" (\n" +
"\t\"Id\"\tINTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n" +
"\t\"Name\"\tTEXT,\n" +
"\t\"Mean\"\tTEXT\n" +
");");
db.execSQL("CREATE TABLE IF NOT EXISTS \"MyList\" (\n" +
"\t\"Id\"\tINTEGER NOT NULL,\n" +
"\t\"Name\"\tTEXT,\n" +
"\t\"Mean\"\tTEXT,\n" +
"\tFOREIGN KEY(\"Id\") REFERENCES \"Words\"(\"Id\"),\n" +
"\tPRIMARY KEY(\"Id\")\n" +
");");
InsertWordToMyList(插入从Words中提取的单词)
ifExists(如果Mylist中存在单词,请勿插入)
FindWord(我的主表是Words,所以我在Words中搜索数据是否存在然后将其拉出)
public String InsertWordToList(DbConnection data,String kelime){
Word yeni=null;
SQLiteDatabase db= data.getWritableDatabase();
ContentValues values= new ContentValues();
String msg;
Boolean bool = ifExists(data,kelime,db);
if(bool){
msg= "kelime zaten var";
}
else {
yeni = FindWord(data, kelime, db);
if(yeni!=null){
Log.e("yeni id",Integer.toString(yeni.getId()));
values.put("Id", yeni.getId());
values.put("Name", yeni.getName());
values.put("Mean", yeni.getMean());
db.insertOrThrow("MyList", null, values);
msg="kelime eklendi";
}
else msg="kelime databasede kayırlı değil";
}
db.close();
return msg;
}
public Word FindWord(DbConnection data, String kelime, SQLiteDatabase db){
Word w= new Word();
//db= data.getWritableDatabase();
Cursor c = db.rawQuery("SELECT * FROM Words WHERE Name = 'kelime'",null);
if(c!=null){
while (c.moveToNext()){
w = new Word(c.getInt(c.getColumnIndex("Id"))
,c.getString(c.getColumnIndex("Name"))
,c.getString(c.getColumnIndex("Mean")));
}
return w;
}
else {
return null;
}
}
public Boolean ifExists (DbConnection data, String kelime, SQLiteDatabase db) {
Word w=null;
Cursor c = db.rawQuery("SELECT * FROM Mylist WHERE Name = 'kelime'",null);
while (c.moveToNext()){
w = new Word(c.getInt(c.getColumnIndex("Id"))
,c.getString(c.getColumnIndex("Name"))
,c.getString(c.getColumnIndex("Mean")));
}
if(w!=null) return true;
else return false;
}
InsertWordToMyList的用法:
for(int i=0;i<get.size();i++){
msg=wordData.InsertWordToMyList(db,get.get(i));
}
答案 0 :(得分:0)
我不知道这是否可以解决您的问题,但由于您的代码正在搜索字符串文字'kelime'
而不是字符串参数kelime
。
像这样更改方法FindWord()
和ifExists()
:
public Word FindWord(DbConnection data, String kelime, SQLiteDatabase db) {
Word w = null;
Cursor c = db.rawQuery("SELECT * FROM Words WHERE Name = ?", new String[] {kelime});
if (c.moveToNext()) {
w = new Word(c.getInt(c.getColumnIndex("Id"))
, c.getString(c.getColumnIndex("Name"))
, c.getString(c.getColumnIndex("Mean")));
}
c.close();
return w;
}
public Boolean ifExists(DbConnection data, String kelime, SQLiteDatabase db) {
Cursor c = db.rawQuery("SELECT * FROM Mylist WHERE Name = ?", new String[] {kelime});
int rows = c.getCount();
c.close();
return rows > 0;
}
我简化了大多数代码,因为您不需要循环。
另外,我也看不到需要参数DbConnection
的地方。