从SQLite Android获取单个记录

时间:2015-04-13 06:02:59

标签: android sqlite

我有一个EditText,我在其上写下我希望在点击按钮后显示在TextView中的记录

所以我需要从My DB和特定列中检索Row记录 我想要检索的是字符串类型 **这是我的查询,但它最适合我**

 public String getCountryCode(String cc) {

 Cursor cursor = null;
 String Code = "";
 try{
     String selectQuery = "SELECT  * FROM " + SQLITE_TABLE + " WHERE "
            + KEY_CODE + " = " + cc;
     cursor = mDb.rawQuery(selectQuery, null);


     if(cursor.getCount() > 0) {

         cursor.moveToFirst();
         Code = cursor.getString(cursor.getColumnIndex("KEY_CODE"));
     }

     return Code;
 }finally {

     cursor.close();
 }
 }

主要活动

b.setOnClickListener(new OnClickListener() {

public void onClick(View arg0) {
// TODO Auto-generated method stub
    try{
String in   =codeinput.getText().toString();
String c    = dbHelper.getCountryCode(in);
CountryShow.setText(c);
}
catch(Exception e ){
    Toast.makeText(listViewDisplay.this, e.getMessage(),      Toast.LENGTH_LONG).show();
}


}
});

3 个答案:

答案 0 :(得分:1)

将查询字符串替换为

String selectQuery = "SELECT  * FROM " + SQLITE_TABLE + " WHERE "
        + KEY_CODE + " = '" + cc+"'";

当您要在查询字符串中添加通用值时,需要在其周围添加单个qouts

答案 1 :(得分:-1)

  1. 尝试将cursor = mDb.rawQuery(selectQuery, null);更改为cursor = mDb.rawQuery(selectQuery, new String[]{});
  2. 我不确定您为什么将KEY_CODE作为" WHERE " + KEY_CODE + " = " + cc;中的变量,您可以将其更改为" WHERE KEY_CODE = " + cc;

  3. 如果KEY_CODE的类型为字符串,则将其更改为String selectQuery = "SELECT * FROM " + SQLITE_TABLE + " WHERE " + KEY_CODE + " = '" + cc + "'";

答案 2 :(得分:-1)

试试这个

if (cursor.moveToFirst()) {
        do {
           // get  the  data into array,or class variable
        } while (cursor.moveToNext());
    }
    db.close();