-2

我创建了一个数据库助手类,我在其中编写了一个这样的选择查询:

//select statement
        public String select(String question_id) {

        SQLiteDatabase db = this.getWritableDatabase(); 


        String sql = "SELECT answer FROM answers WHERE _id="+question_id;
         Log.i("select: ",sql);

        db.close();
        return sql;

}

这就是我从活动中调用 select 方法的方式

//select statement to retrive previous answer from database
                DataBaseHelper db = new DataBaseHelper(ExamActivity.this);
                ContentValues values = new ContentValues();
                try {
                 db.createDataBase();
                 chk_content = db.select(question_sr_no.getText().toString()); 

                } catch (IOException e1) {
                 e1.printStackTrace();
                  }
                db.close();

但是logcat的输出是:

SELECT answer FROM answers WHERE _id=1.

为什么查询不返回结果,而是返回查询字符串?

提前致谢!

4

3 回答 3

2

您忘记使用db.rawQuery. 将您的方法更改为:

public String select(String question_id) {
   SQLiteDatabase db = this.getWritableDatabase(); 
   String str_answer="";
   String sql = "SELECT answer FROM answers WHERE _id="+question_id;
   Log.i("select: ",sql);
   Cursor cursor = db.rawQuery(sql, null); //<< execute here 
   cursor.moveToFirst();
   if (cursor.getCount()>0) {
      str_answer=cursor.getString(cursor.getColumnIndex("answer");
    }
  return str_answer;
}
于 2013-03-19T12:49:30.983 回答
0

你只是记录,你没有调用查询方法

于 2013-03-19T12:49:11.717 回答
0

您的 select 方法只是创建一个字符串并返回该字符串。看看你自己的代码。

 //select statement
    public String select(String question_id) {

    SQLiteDatabase db = this.getWritableDatabase(); 

    String sql = "SELECT answer FROM answers WHERE _id="+question_id; //you return this. 
     Log.i("select: ",sql);

    db.close();
    return sql;

}

我猜你想要的是实际查询数据库,而不仅仅是打开它然后再次关闭它。

于 2013-03-19T12:50:33.860 回答