插入如果不存在:SQLite



如果该标题还不存在,我想插入数据。

这是我得到的书面查询的错误:

near "with":语法错误(代码1):,编译时:SELECT * FROM movie WHERE headline=Albert Collen

代码:

public boolean Insert(Item item) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM " + TABLE + " WHERE headline=" + item.getName() , null);
if (cursor.moveToFirst()) {
} else {
contentValues.put("name", item.getName());           
long result = sqLiteDatabase.insert(TABLE, null, contentValues);
if (result == -1) {
return false;
} else {
return true;
}
}
cursor.close();
sqLiteDatabase.close();
return true;
}

应该使用查询参数

rawQuery("SELECT * FROM movie WHERE headline = ?", new String[] {"Albert Collen"});

避免转义引号和其他字符。

首先,结果查询错误。所有的字符串常量都要加引号,像这样

SELECT * FROM movie WHERE headline='Albert Collen';

所以,试着写这样的查询,也许它会有帮助

Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM " + TABLE + " WHERE headline='" + item.getName() + "'" , null);

但是连接一个查询并不是一个好主意,因为它至少使sql注入成为可能。

例如,当item.getName()包含以下行"';Drop table movies;">

更好的选择是使用绑定查询变量。不幸的是,我不熟悉如何使用java-android与sqlite,所以你最好检查如何在android中使用这样的查询

最新更新