Android错误查询SQLite

时间:2014-04-08 09:04:32

标签: android sqlite

您好我有这样的查询:

String sql ="SELECT _id, field10, field11, SUM(field2) FROM Table WHERE field2>0 AND data LIKE '"+anno+"-%'";

如果在数据库中,它存储了一个像这样的字符串(pubblicita')我会得到这样的语法错误:

 Caused by: android.database.sqlite.SQLiteException: near "2014": syntax error (code 1): , while compiling:
 SELECT _id, field10, field11, SUM(field2) FROM Table WHERE field2>0 AND field10 LIKE 'PUBBLICITA'' AND data LIKE '2014-%'

问题在于顶点,我该如何解决这个问题?

更新 不幸的是,所有答案都是错误的。如果字符串对应于顶点,则会生成错误。看图像 enter image description here

4 个答案:

答案 0 :(得分:1)

在SQL字符串文字中,引号必须通过加倍来转义。

但是,您可以通过将字符串作为parameter

传递来避免手动执行此操作
cursor = db.rawQuery("SELECT ... data LIKE ? || '-%'",
                     new String[] { anno });

答案 1 :(得分:0)

在使用sql中的字符串之前,你需要转义引号字符。

public static String escapeSQLQuotes(final String in) {
    return in.replaceAll("'", "''");
}

并使用:

String sql ="SELECT _id, field10, field11, SUM(field2) FROM Table WHERE field2>0 AND data LIKE '"+escapeSQLQuotes(anno)+"-%'";

答案 2 :(得分:-1)

试试:

String sql ="SELECT _id, field10, field11, SUM(field2) FROM Table WHERE field2>0 AND data LIKE '"+anno+"%'";

"-%'" replace "%'"

答案 3 :(得分:-1)

"-%"替换为"%"

String sql ="SELECT _id, field10, field11, SUM(field2) FROM Table WHERE field2>0 AND data*  LIKE '"+anno+"%'";