简体   繁体   中英

Update query sqlite - Android

I'm not able to crack a simple Update query in SQLite in my android app.. here is the query,

int fav = 1;
Cursor c = sqliteDB.rawQuery("UPDATE "+ MyConstants.TABLE_NAME + " SET "+MyConstants.TABLE_NAME+"."+MyConstants.ISFAV+ " = "+fav+ " WHERE " +MyConstants.TABLE_NAME+"."+MyConstants.WORD_NAME+ " = \""+word_name+"\"", null);

Here is the exception,

07-06 23:41:48.723: E/AndroidRuntime(1102): FATAL EXCEPTION: main
07-06 23:41:48.723: E/AndroidRuntime(1102): android.database.sqlite.SQLiteException: near ".": syntax error (code 1): , while compiling: UPDATE words SET words.isfavor = 1 WHERE words.word = "hello"
07-06 23:41:48.723: E/AndroidRuntime(1102):     at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
07-06 23:41:48.723: E/AndroidRuntime(1102):     at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1013)
07-06 23:41:48.723: E/AndroidRuntime(1102):     at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:624)
07-06 23:41:48.723: E/AndroidRuntime(1102):     at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
07-06 23:41:48.723: E/AndroidRuntime(1102):     at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
07-06 23:41:48.723: E/AndroidRuntime(1102):     at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
07-06 23:41:48.723: E/AndroidRuntime(1102):     at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)

You keep using the table name inappropriately. It should be more like this:

int fav = 1;
Cursor c = sqliteDB.rawQuery("UPDATE "+ MyConstants.TABLE_NAME + " SET "+ MyConstants.ISFAV + " = "+fav+ " WHERE " + MyConstants.WORD_NAME + " = \""+word_name+"\"", null);

which should give you a resultant query that looks more like this:

UPDATE words SET isfavor = 1 WHERE word = "hello"
  1. UPDATE statements always have only one table, so prefixing column names with table names would be meaningless and is not allowed.
  2. In SQL, strings are delimited with ' . " is used for identifiers like column names; your query will blow up when you try to handle the word word .
  3. To avoid string formatting problems, you should use parameters:
    sqliteDB.rawQuery("UPDATE ... WHERE word = ?",
                      new String[] { word_name });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM