android.database.sqlite.SQLiteException:near"...":语法错误(代码1)

men*_*top 3 database sqlite android

当我打开我的RSS应用程序时,我想检查我的数据库中是否存在一篇文章.如果它存在,我想删除它(或忽略它),如果不在数据库中写入它.

我一直试图这样做:

            Cursor cursor = ourDatabase.rawQuery("select 1 from "
                    + DBHelper.DATABASE_TABLE + " where " + DBHelper.TITLE + "='"
                    + title + "'" + " AND " + DBHelper.DATE + "='" + date + "'",
                    new String[] {});
            if (cursor.moveToFirst()) {
                boolean exists = (cursor.getCount() > 0);
                cursor.close();
                return exists;
            } else {
    return false;       }

        }
Run Code Online (Sandbox Code Playgroud)

但我得到这个错误:

06-06 16:01:11.341: E/AndroidRuntime(13867): Caused by: android.database.sqlite.SQLiteException: near "???": syntax error (code 1): , while compiling: select 1 from all_t where title='? ????? ??? ? ?????? ??? ??????????!!! ????? ?? ???????? ????? ??? ??????? ??' ??? ????????!' AND date='Wed, 05 Jun 2013 18:12:15'
Run Code Online (Sandbox Code Playgroud)

njz*_*zk2 10

这是一个典型的问题,没有使用它selectionArgs,这正是为什么人们应该使用它们:你用简单的引号引用你的字符串,但你的字符串包含单引号,所以SQLite在实际结束之前检测字符串的结尾,并且尝试将其余部分解析为SQLite关键字.

正确的解决方案是通过使用那些selectionArgs尝试逃避自我的方式将逃逸留给SQ​​Lite .在你的情况下,那将是:

Cursor cursor = ourDatabase.rawQuery("select 1 from "
            + DBHelper.DATABASE_TABLE + " where " + DBHelper.TITLE + "=?"
            + " AND " + DBHelper.DATE + "=?",
            new String[] {title, date});
Run Code Online (Sandbox Code Playgroud)

此外,它更干净,因为您可以从查询中获取常量而不是每次构建它.


War*_*ith 6

除非您别无选择,否则请勿使用原始查询!

Cursor findEntry = db.query(TABLE, columns, DBHelper.TITLE + "=?", new String[] { title }, null, null, null);
Run Code Online (Sandbox Code Playgroud)

或多种东西

Cursor findEntry = db.query((TABLE, columns, DBHelper.TITLE + "=? and " + DBHelper.DATE + "=?", new String[] { title, date}, null, null, null);
Run Code Online (Sandbox Code Playgroud)