E / SQLiteLog:(1)无法识别的令牌:“:”

时间:2019-11-23 19:21:22

标签: android sqlite exception

我正在尝试查询一个字符串,该字符串的值对应于sqlite / android studio中的url地址,但它始终引发异常:

E/SQLiteLog: (1) unrecognized token: ":"
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.project, PID: 4525
    android.database.sqlite.SQLiteException: unrecognized token: ":" (code 1): , while compiling: SELECT  * FROM URLS_ITEMS WHERE title = Google AND url = http://www.google.com;
    #################################################################
    Error Code : 1 (SQLITE_ERROR)
    Caused By : SQL(query) error or missing database.
        (unrecognized token: ":" (code 1): , while compiling: SELECT  * FROM URLS_ITEMS WHERE title = Google AND url = http://www.google.com;)
    #################################################################
        at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
        at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1096)
        at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:661)

下面是引发异常的代码段:

public boolean isUrlAlreadyStored(String title, String url) {
        ArrayList<URLItem> urlDetailList = new ArrayList<URLItem>();
        String query = "SELECT  * FROM " + DATABASE_TABLE_URLS_ITEMS + " WHERE title = " + title + " AND url = " + url + ";";
        Cursor cursor = database.rawQuery(query, null);

我想我应该逃脱字符/令牌:但不确定如何。我尝试过:url = url.replaceAll(“:”,“:”),但显然这不是正确的方法。

有人知道如何查询“ https://www.stackoverflow.com”这样的值/字符串吗?

2 个答案:

答案 0 :(得分:0)

您可以为SQLite的字符串数据类型添加“'”单引号。

String query = "SELECT  * FROM " + DATABASE_TABLE_URLS_ITEMS + " WHERE title = '" + title + "' AND url = '" + url + "';";

答案 1 :(得分:0)

titleurl的值是字符串文字,应该用单引号引起来:

String query = "SELECT  * FROM " + DATABASE_TABLE_URLS_ITEMS + " WHERE title = '" + title + "' AND url = '" + url + "';";
Cursor cursor = database.rawQuery(query, null);

但是推荐的安全方法是在语句内使用占位符?,并在title的第二个参数中传递urlrawQuery()的值:

String query = "SELECT  * FROM " + DATABASE_TABLE_URLS_ITEMS + " WHERE title = ? AND url = ?;";
Cursor cursor = database.rawQuery(query, new String[] {title, url});