简体   繁体   中英

Escape special character # in table condition clause

Creating the table in SQLite with column names which contains special character # .

Don't know how to escape this so that SQLite recognize it.

I found that the escape code for # is %23 . So I tried to do like this:

condition = condition.replace("usernum#", "usernum%23");

where condition is the SQLite condition of type string, for example, select * from users where id = '2' ORDER BY usernum#

But the above way is giving SQLite Exception.

LOG:

04-12 20:00:44.395: E/AndroidRuntime(8054): android.database.sqlite.SQLiteException: no such column: usernum (code 1): , while compiling: select * from Users WHERE id !=1 order by Type DESC, usernum%23 ASC

Error is in this line:

Cursor curr = db.rawQuery("select " + fields + " from " + table + " "+ condition, null);

04-12 20:00:44.395: E/AndroidRuntime(8054): android.database.sqlite.SQLiteException: no such column: usernum (code 1): , while compiling: select * from Users WHERE id !=1 order by Type DESC, usernum%23 ASC

Since column contains special character, solution is to wrap it to double quotes(whole column) and it will work

select * from test order by "username#" desc;

In your case:

String query = "Select * from users where id = ? ORDER BY \"usernum#\"";
Cursor c = db.rawQuery(query, new String[] {String.valueOf(id)});

Solution with query() method:

String[] columns = {...};
String selection = idColumn + " = ?";
String[] args = {String.valueOf(id)};
String orderBy = "\"" + orderByColumn + "\"";
Cursor c = db.query(table, columns, selection, args, null, null, orderBy);

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