且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如果不存在的Andr​​oid SQLite的插入记录

更新时间:2023-10-10 23:28:52

我想你可能需要周围的变量单引号的项目的,只要它出现,因为它的值没有列名。
试试这个code:

 公共无效populate_base_lists2(字符串表名,字符串项){
ourDatabase.execSQL(插入+表名+
(+ KEY_NAME_PR +)SELECT * FROM(SELECT'+项目+')
WHERE NOT EXISTS(
选择+ KEY_NAME_PR +
FROM+表名+WHERE+ KEY_NAME_PR +='+项目+'
)LIMIT 1;);
}

希望有所帮助。

I want to add a new item (Cheese) to an sqlite table but only in case it does not exist. I have two columns only in the table: _id (KEY_ROWID_PR) and product_name (KEY_NAME_PR).

I've been trying with these code, but it gives me an error:

public void populate_base_lists2(String tablename, String item) {
        ourDatabase.execSQL("INSERT INTO " + tablename + " (" + KEY_NAME_PR + ") SELECT * FROM (SELECT " + item  + ") WHERE NOT EXISTS (SELECT " + KEY_NAME_PR + " FROM " + tablename + " WHERE " + KEY_NAME_PR + " = " + item + ") LIMIT 1;");
}

03-11 17:27:20.972: E/AndroidRuntime(658): Caused by: android.database.sqlite.SQLiteException: no such column: Cheese: INSERT INTO PR_Dairy_Products (product_name) SELECT * FROM (SELECT Cheese) WHERE NOT EXISTS (SELECT product_name FROM PR_Dairy_Products WHERE product_name = Cheese) LIMIT 1;

The code is from here: MySQL: Insert record if not exists in table

no such column: Cheese, ok, I changed that part to KEY_NAME_PR, then the error was the same, but with no such column: product_name. That column definitely exists.

What is more, I need some explanation on this code. I have sql knowledge on a certain level, but I cannot get this.

Thanks

I think you may need single quotes around the variable item whenever it appears because it a value not a column name. Try this code:

public void populate_base_lists2(String tablename, String item) {
ourDatabase.execSQL("INSERT INTO " + tablename +
" (" + KEY_NAME_PR + ") SELECT * FROM (SELECT '" + item  + "')
WHERE NOT EXISTS (
SELECT " + KEY_NAME_PR +
" FROM " + tablename + " WHERE " + KEY_NAME_PR + " = '" + item + "'
) LIMIT 1;");
}

Hope that helps.