SQLite选择问题

时间:2011-10-30 09:39:48

标签: android sqlite

我写的方法应该返回带有来自select查询的数据的字符串,但它并不像我想的那样完美地工作,这里是方法:

public String selectorDanych(String kolumna, String log){
String test = "Select "+ kolumna + " from "+ Usr_TABLE+ " where "+colLogin + " ='" +log+"';";
Cursor cursor2 = sqLiteDatabase.rawQuery(test, null);
return cursor2.toString();
}

它返回某种字符串但是,它不是我想要的东西[它返回的字符串类似于“SQLite.database。@”等

3 个答案:

答案 0 :(得分:1)

您将返回从查询中获得的Cursor的内部名称,而不是查询结果中的任何数据。

你应该使用类似的东西:

cursor2.moveToFirst(); // position the cursor at the first returned row
String col = cursor2.getString(the_index_of_the_column_you_want);
cursor2.close();
return col;

请确保您测试错误(可能根本没有返回任何行),并阅读Cursor API文档。

答案 1 :(得分:0)

将代码重写为

public String selectorDanych(String kolumna, String log){
    String test = "Select "+ kolumna + " from "+ Usr_TABLE+ " where "+colLogin + " ='" +log+"';";
    Cursor cursor2 = sqLiteDatabase.rawQuery(test, null);

//Write these codes
if(cursor2.moveToFirst()) {
   cursor2.close();             //You should close your cursor
   return cursor2.getString(0); //index of your kolumna field
} else {
   cursor2.close();             //You should close your cursor
   return null; //Return some error msg, to notify that data not found
}
}

答案 2 :(得分:0)

您可以使用以下代码。您可以在try块之后捕获异常。即使你不这样做,你也可以保证调用光标上的close()!我还建议你总是使用英文名称。

    public String selectorDanych(String kolumna, String log){
    String test = "Select "+ kolumna + " from "+ Usr_TABLE+ " where "+colLogin + " ='" +log+"';";
    Cursor cursor2 = sqLiteDatabase.rawQuery(test, null);

  if (cursor2 != null && cursor2.moveToFirst()) { 
      try { //use try - finally to close the cursor in the finally block
        int index_kolumna = cursor2.getColumnIndexOrThrow(kolumna);
        String kolumna_val = cursor2.getString(index_kolumna);  
      } finally { 
        if (cursor2 != null && !cursor2.isClosed()) {
        cursor2.close();
      }
   }

}