虽然尝试实现SQLite存储遇到了奇怪的行为。 “?” - 符号不能替代。
我的代码:
public class DBHandler extends SQLiteOpenHelper {
public void writeTask(JSONObject object) throws JSONException {
SQLiteDatabase db = this.getWritableDatabase();
String id = object.get(OBJECT_ID).toString();
String content = object.toString();
String md5 = "md5"; //testing
Cursor c = db.rawQuery("INSERT OR REPLACE INTO ? ( ? , ? , ? ) VALUES ( ? , ? , ?);", new String[] {TABLE_OBJECTS, OBJECT_ID, OBJECT_CONTENT, OBJECT_MD5, id, content, md5 });
}
}
然后它抛出一个奇怪的错误:
android.database.sqlite.SQLiteException: near "?": syntax error (code 1): , while compiling: INSERT OR REPLACE INTO ? ( ? , ? , ? ) VALUES ( ? , ? , ?);
第一个错误已得到纠正,但仍无效:
String selectQuery = "INSERT OR REPLACE INTO " + TABLE_OBJECTS + " ("
+ OBJECT_ID + "," + OBJECT_CONTENT + "," + OBJECT_MD5 + ") "
+ "VALUES ( ? , ? , ?);";
String[] args = { id, content, md5 };
Log.d("FP", selectQuery);
Cursor c = db.rawQuery(selectQuery,args);
此查询后,数据库不受影响。日志显示我的查询:
INSERT OR REPLACE INTO objects (id,content,md5) VALUES (?,?,?);
有什么建议吗?
所以, rawQuery()仅适用于 SELECT 。
但是我仍然需要转义特殊字符,因为内容 -variable是一个字符串化的JSON,而execSQL不允许这样做。
答案 0 :(得分:6)
您只能将?
用于绑定文字,例如VALUES()
中的文字,而不能用于SQL中较早的表名或列名等标识符。
如果需要将变量用于标识符,请在Java中使用常规字符串连接。
另请注意,仅rawQuery()
不会执行您的SQL。请考虑改为使用execSQL()
。