我试图通过在where子句中传递“id”号来从表中检索数据 sqlite android,但是得到空的结果。
如果我将另一个字段(名称,数字)作为where子句传递。它工作正常,但不适用于id。
这是表格的代码:
public final String field_id = "id";
public final String field_name = "name";
public final String field_no = "no";
String create_query = "CREATE TABLE " + TABLE_NAME + "("
+ field_id + " INTEGER PRIMARY KEY autoincrement,"
+field_name+ " TEXT,"
+ field_no + " TEXT"
+ ")";
以下是检索数据的代码
Cursor editData(String id)
{
Log.d(TAG, "editData() called");
SQLiteDatabase db = this.getReadableDatabase();
String search_query = "SELECT * FROM "+ TABLE_NAME +" WHERE id=?";
Cursor cursor = db.rawQuery(search_query,new String []{id});
if(cursor == null)
{
Log.d(TAG, "cursor is NULL");
return null;
}
return cursor;
}
以下是我使用此结果的方法
DBHelper mDB = new DBHelper(this);
Cursor mCursor = mDB.editData(id_name.getText().toString());
if(mCursor.moveToFirst())
{
Log.d("EditActivity", "cursor moved to first");
Log.d("TAG",String.format("%d", mCursor.getCount()));
//Solved this by using Do...While loop instead of while
while(mCursor.moveToNext())
{
Log.d("EditActivity", "cursor moved to next");
Log.d(mCursor.getColumnName(0), mCursor.getString(0));
Log.d(mCursor.getColumnName(1), mCursor.getString(1));
Log.d(mCursor.getColumnName(2), mCursor.getString(2));
}
}
我们不能在sqlite的where子句中使用自动生成的id吗? 对此有何帮助?
编辑:我使用while while循环而不是while&它起作用了
答案 0 :(得分:0)
之前发生在我身上。数据库 id 是数字,函数是 string 。
这里的问题是你制作这段代码的时候:
String search_query = "SELECT * FROM "+ TABLE_NAME +" WHERE id=?";
Cursor cursor = db.rawQuery(search_query,new String []{id});
最终查询是...... "SELECT * FROM "+ TABLE_NAME +" WHERE id='1'";
你真正想要的是"SELECT * FROM "+ TABLE_NAME +" WHERE id=1";
这是我的解决方案......
String search_query = "SELECT * FROM "+ TABLE_NAME +" WHERE id="+id;
Cursor cursor = db.rawQuery(search_query,null);
或
String search_query = "SELECT * FROM "+ TABLE_NAME +" WHERE cast(id as text)=?";
Cursor cursor = db.rawQuery(search_query,new String []{id});