android.database.sqlite.SQLiteException: near “…”: syntax error (code 1)

后端 未结 4 647
猫巷女王i
猫巷女王i 2021-01-14 15:19

When i open my RSS app, i would like to check if an article exists in my database.If it exists,i would like to delete it (or ignore it),if not to write it in the db.

相关标签:
4条回答
  • 2021-01-14 15:52

    This is a typical issue with not using the selectionArgs, and it is exactly why one should use them: You are quoting your string with simple quotes, but your string contains single quote, so SQLite detect the end of the string before it actually ends, and try to parse the rest as SQLite keyword.

    The proper solution is to leave the escaping to SQLite, by using those selectionArgs rather that trying to do the escaping your self. in you case, that would be :

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

    plus, it's cleaner because you can make a constant out of your query rather than constructing it every time.

    0 讨论(0)
  • 2021-01-14 15:53

    You have to escape the ' character or it breaks your SQL.

    near "όσο": syntax error (code 1): , while compiling: select 1 from all_t where title='Ο ΦΟΒΟΣ και ο ΤΡΟΜΟΣ των διαδηλωτών!!! Αυτές οι γυναίκες είναι πιο σκληρές απ' όσο δείχνουν!'

    More info here.

    Perhaps instead of directly manipulating strings in a rawQuery you can look into using a preparedStatement?

    How do I use prepared statements in SQlite in Android?

    0 讨论(0)
  • 2021-01-14 15:54

    The answers given so far are correct, but you would be much better off using a parameterised query. There is no extra work involved - indeed it is easier that their suggestions of escaping the single quotes.

    0 讨论(0)
  • Don't use the raw query unless you have no other choice!

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

    or for multiple stuff

    Cursor findEntry = db.query((TABLE, columns, DBHelper.TITLE + "=? and " + DBHelper.DATE + "=?", new String[] { title, date}, null, null, null);
    
    0 讨论(0)
提交回复
热议问题