0

在 SQLite 中使用包含特殊字符的列名创建表#

不知道如何逃避这个以便 SQLite 识别它。

我发现转义码#%23. 所以我试着这样做:

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

其中 condition 是字符串类型的 SQLite 条件,例如,select * from users where id = '2' ORDER BY usernum#

但是上面的方法是给 SQLite 异常。

日志:

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

错误在这一行:

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

1 回答 1

0

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

由于列包含特殊字符,解决方案是将其包装到双引号(整列)并且它将起作用

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

在你的情况下:

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

使用 query() 方法的解决方案:

String[] columns = {...};
String selection = idColumn + " = ?";
String[] args = {String.valueOf(id)};
String orderBy = "\"" + orderByColumn + "\"";
Cursor c = db.query(table, columns, selection, args, null, null, orderBy);
于 2013-04-12T14:37:42.667 回答