SQLiteException: Unrecognized token when reading from database

倾然丶 夕夏残阳落幕 提交于 2019-12-21 16:49:11

问题


I've created an SQLite database inside application, populated it and now I'm trying to read from it. The app keeps crashing and this is the logcat I receive:

12-30 05:53:18.008: E/AndroidRuntime(6205): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.testparsing/com.example.testparsing.Urnik}: android.database.sqlite.SQLiteException: unrecognized token: "4c" (code 1): , while compiling: SELECT predmet FROM predmeti WHERE dan=PONEDELJEK and ura=2 and oddelek=4c

Function for reading from database:

Cursor getSubject(String dan, int ura, String oddelek){
    String[] columnNames = new String[1];
    columnNames[0] = SQLiteHelper.PREDMET;
    String selection = SQLiteHelper.DAN+"="+dan+" and "+SQLiteHelper.URA+"="+ura+" and "+SQLiteHelper.ODDELEK+"="+oddelek;
    open();
    return db.query(
            SQLiteHelper.IME_TABELE, 
            columnNames, 
            selection, 
            null, null, null, null);
}

How I'm trying to read:

TextView tw1p = (TextView) findViewById(R.id.tview1p);
DatabaseHandler db = new DatabaseHandler(getApplicationContext());

Cursor c = db.getSubject("PONEDELJEK", 2, "4c");
String predmet = c.getString(c.getColumnIndex(SQLiteHelper.PREDMET));
tw1p.setText(predmet);

A screenshot of table, just to prove that oddelek "4c" in fact does exist:


回答1:


SELECT predmet FROM predmeti WHERE dan=PONEDELJEK and ura=2 and oddelek=4c

You need to quote your string literals, for example:

SELECT predmet FROM predmeti WHERE dan='PONEDELJEK' and ura=2 and oddelek='4c'

But it's better to use ? placeholder for literals:

SELECT predmet FROM predmeti WHERE dan=? and ura=? and oddelek=?

and change your null selectionArgs to

new String[] { dan, Integer.toString(ura), oddelek }



回答2:


String selection = SQLiteHelper.DAN+"="+dan+" and "+SQLiteHelper.URA+"="+ura+" and "+SQLiteHelper.ODDELEK+"='"+oddelek+"'";

Replace with this and check




回答3:


issue is due to missing quotes only :-

Example

 db.delete(TABLE_NA,E, ADDRESS + "= '" + address + "'", null);

Please check below field + "= '" + address + "'"

{Issue as address is string so it should be under 'address' }



来源:https://stackoverflow.com/questions/20838233/sqliteexception-unrecognized-token-when-reading-from-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!