【问题标题】:How to implement where clause on Android Query method?如何在 Android Query 方法上实现 where 子句?
【发布时间】:2011-03-29 16:15:35
【问题描述】:

我正在尝试查询一个单词,为此我使用了 db.query 方法。但我想使用 WHERE 子句。我已经在我的代码上这样做了,但我想我的 WHERE 子句有问题。

public String select(String wrd) {
  String list = new String();
  Cursor cursor = this.db.query(TABLE_NAME, new String[] {"word"}, 
    "word like " + wrd + "", null, null, null, "id desc");
  if (cursor.moveToNext()) {
     do {
        list = cursor.getString(0); 
     } while (cursor.moveToNext());
  }
  if (cursor != null && !cursor.isClosed()) {
     cursor.close();
  }
  return list;

}

我在其他类中调用这个方法,解析一个字符串参数。

Cursor cursor = getContentResolver().query(CONTENT_URI, null, null, null, null);                                    
        String body;                                        
        if(cursor.moveToFirst()){
            body = cursor.getString(cursor.getColumnIndexOrThrow("body")).toString();
            if(body == ""){
                Toast.makeText(getBaseContext(), "There is no words to save!", Toast.LENGTH_LONG).show();
            }
                else{
                    String words = this.dh.select("Testando");
                    StringTokenizer st = new StringTokenizer(body);
                    while(st.hasMoreTokens()){
                         if(words == st.nextToken())
                         Toast.makeText(getBaseContext(), "found! "+words+"", Toast.LENGTH_LONG).show();
                         this.dh.insert(st.nextToken());                             
                         Toast.makeText(getBaseContext(), "The set of words has been updated!", Toast.LENGTH_LONG).show();                                                                                                              
                    }                       
                    StringBuilder sb = new StringBuilder();
                    sb.append("Set of words:\n\n");
                    sb.append(words + " ");                    
                    txtView.setText(sb.toString());
                }
        }  

【问题讨论】:

  • 你遇到了什么错误?
  • “模拟器返回错误”——你应该包含错误信息然后...

标签: android database sqlite select


【解决方案1】:

我认为问题与以下代码中的双引号有关:

Cursor cursor = this.db.query(TABLE_NAME, new String[] {"word"}, 
    "word like " + wrd + "", null, null, null, "id desc");

试试这个

Cursor cursor = this.db.query(TABLE_NAME, new String[] {"word"}, 
    "word like \"" + wrd + "\"", null, null, null, "id desc");

甚至更好

Cursor cursor = this.db.query(TABLE_NAME, new String[] {"word"}, 
        "word like ?",new String[] {wrd} , null, null, "id desc");

编辑:

在 WHERE 子句中使用单引号而不是双引号。见here

Cursor cursor = this.db.query(TABLE_NAME, new String[] {"word"}, 
    "word like \'" + wrd + "\'", null, null, null, "id desc");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    • 2015-06-26
    • 2018-09-17
    • 2021-07-23
    • 2017-01-30
    • 2020-01-28
    • 1970-01-01
    相关资源
    最近更新 更多