我正在使用Android进行开发,我需要使用类似运算符和变量对sqlite进行查询。
我尝试修改的代码片段是this link.
处的数据库的实现所以,我正在尝试对链接中创建的表进行查询,以便从表中只选择一个名称。我这样做:
Cursor c = sampleDB.rawQuery("SELECT FirstName, Age FROM " +
SAMPLE_TABLE_NAME + " where" +field+ " like %"+search+"%" , null);
其中字段和搜索是以这种方式定义的两个变量:
final String field = "LastName";
final String search = "Makam";
如果我在输出中执行应用程序,我应该看到一行中包含我在查询中选择的名称和年龄。但是,我什么都没得到!
Logcat of Eclipse
显示:
sqlite returned: error code = 1,msg = near "like": syntax error.
但我很确定它的语法是正确的。有人能帮助我吗?
答案 0 :(得分:7)
使用这种方式:
Cursor c = sampleDB.rawQuery("SELECT FirstName, Age FROM " +
SAMPLE_TABLE_NAME + " where " +field+ " like '%"+search+"%'" , null);
public Cursor getSearch(String SAMPLE_TABLE_NAME, String field,
String search) {
SQLiteDatabase sampleDB = this.getReadableDatabase();
Cursor c = sampleDB.rawQuery("SELECT FirstName, Age FROM "
+ SAMPLE_TABLE_NAME + " where " + field + " like '%" + search
+ "%'", null);
return c;
}
答案 1 :(得分:3)
在我看来,好像您可能错过WHERE
和field
之间的空格。
答案 2 :(得分:2)
selection.append(column_name).append(" like ?");
selectionArgs = new String[]{"%" + mCategoryName + "%"};
db.query(TABLE_URI,null,selection.toString(),selectionArgs,null);
答案 3 :(得分:1)
试试这个:
final String field = "LastName";
final String search = "Makam";
String query = "SELECT FirstName, Age FROM " +
SAMPLE_TABLE_NAME + " where " +field+ " like '%+search+%'";
Cursor c = sampleDB.rawQuery(query,null);
一切顺利!