我创建了一个数据库帮助器类,我在其中编写了一个选择查询,如下所示:
//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.
为什么查询不返回结果,而是返回查询字符串?
提前致谢!
答案 0 :(得分: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;
}
答案 1 :(得分:0)
您只是在记录,而不是在调用query method。
答案 2 :(得分: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;
}
我猜你所追求的是实际查询数据库,而不仅是打开它并再次关闭它。