说我有这样的帮手:
public class SqlHelper extends SQLiteOpenHelper {
public SqlHelper(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE MyTable (ID INTEGER PRIMARY KEY, NAME TEXT, PLACE TEXT)");
db.execSQL("INSERT INTO MyTable (NAME, PLACE) VALUES('ANTHONY','USA')");
db.execSQL("INSERT INTO MyTable (NAME, PLACE) VALUES('BERIMOR','UK')");
db.execSQL("INSERT INTO MyTable (NAME, PLACE) VALUES('IVAN','RUSSIA')");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
在我的主代码中执行查询
SqlHelper sqlHelper = new SqlHelper(this, "MyDataBase.db", null, 1);
SQLiteDatabase DB = sqlHelper.getReadableDatabase();
Cursor c = DB.query(
"MyTable" /* table */,
new String[] { "PLACE" } /* columns */,
"id = ?" /* where or selection */,
new String[] { "RUSSIA" } /* selectionArgs */,
null /* groupBy */,
null /* having */,
null /* orderBy */
);
DB.close();
但我不确定那个光标是什么?它不应该像数组吗?如果是这样,我如何从中获取原始值(字符串)?像这样的查询应该返回'IVAN'。
谢谢!
EDIT2:
这个(c.getCount())仍然返回0,即没有结果...嗯......也许那里有帮手的东西?
Cursor c = DB.query(
"MyTable" /* table */,
new String[] { "NAME" } /* columns */,
"PLACE = 'RUSSIA'" /* where or selection */,
null /* selectionArgs */,
null /* groupBy */,
null /* having */,
null /* orderBy */
);
Log.e("DB RETURNS", String.valueOf( c.getCount() ) );
答案 0 :(得分:2)
游标是指向查询结果集的指针。阅读Cursor文档: http://developer.android.com/reference/android/database/Cursor.html
基本上,你会做类似的事情:
String place;
if (c.moveToFirst){
place = c.getString( c.getColumnIndex("PLACE"));
}
答案 1 :(得分:2)
查询返回的Cursor对象提供对记录集的访问 结果。
获得Cursor后,必须遍历它以获取值。在你的情况下,你会这样做 -
if (cur.moveToFirst()) {
int placeColumn = cur.getColumnIndex("PLACE");
String place = cur.getString(placeColumn);
}
要根据PLACE的查询取出NAME,您应该PLACE = ?
Cursor c = DB.query(
"MyTable" /* table */,
new String[] { "NAME" } /* columns */,
"PLACE = ?" /* where or selection */,
new String[] { "RUSSIA" } /* selectionArgs */,
null /* groupBy */,
null /* having */,
null /* orderBy */
);