2015-09-06 40 views
-1

在我的項目,我用這遊標查詢:如何在使用遊標查詢時解決sqlite中的語法異常?

Cursor c = db.query(VivzHelper.TX_TABLE, columns, helper.TX_ID + "='" + name + "' AND " + helper.TX_DATE + " BETWEEN '"+ datefrom.from_date + "' AND '" + dateto.to_date + "' AND '"+ helper.TX_TYPE +" = '"+"DM", null, helper.TX_NAME, null, null); 

我得到了我上面的查詢以下異常:

android.database.sqlite.SQLiteException: near "DM": syntax error (code 1): , while compiling: SELECT _id, txname, SUM(amount) AS amount, date, txtype FROM transactions WHERE txid='E' AND date BETWEEN '2015-09-06' AND '2015-09-06' AND 'txtype = 'DM GROUP BY txname 
+0

你爲什麼不使用'selectionArgs'參數? – pskink

回答

1

請參見本部分:

AND 'txtype = 'DM GROUP BY txname 

應:

AND txtype = 'DM' GROUP BY txname 

的錯誤是在這裏:

AND '"+ helper.TX_TYPE +" = '"+"DM", null, 

應該是:

Cursor c = db.query(VivzHelper.TX_TABLE, columns, helper.TX_ID + "='" + name + "' AND " + helper.TX_DATE + " BETWEEN '"+ datefrom.from_date + "' AND '" + dateto.to_date + "' AND '"+ helper.TX_TYPE +" = '"+"DM", null, helper.TX_NAME, null, null); 

這樣::

AND "+ helper.TX_TYPE +" = 'DM'", null, 

所以,從這個解決您的rawQuery

Cursor c = db.query(VivzHelper.TX_TABLE, columns, helper.TX_ID + "='" + name + "' AND " + helper.TX_DATE + " BETWEEN '"+ datefrom.from_date + "' AND '" + dateto.to_date + "' AND "+ helper.TX_TYPE +" = 'DM'", null, helper.TX_NAME, null, null); 

[編輯]

使用約束參數(AKA selectionArgs兩個)將幫助你擺脫字符串分隔符:

Cursor c = db.query(VivzHelper.TX_TABLE, columns, helper.TX_ID + " = ? AND " + helper.TX_DATE + " BETWEEN ? AND ? AND "+ helper.TX_TYPE + " = ?", new String[]{name, datefrom.from_date, dateto.to_date, "DM"}, helper.TX_NAME, null, null); 
+0

你能告訴如何在查詢中做到這一點嗎? – Rajendran

+0

你建議不要使用'selectionArgs',這不好 – pskink

+0

我會建議**綁定參數**,作爲編輯 –