Android's SQLite, how to turn Cursors into strings?
Say I have such helper:
public class SqlHelper extends SQLiteOpenHelper {
public SqlHelper(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
// TODO Auto-generated开发者_JAVA百科 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
}
}
and in my main code I execute a query
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();
But I'm not sure what that cursor thing is? Shouldn't it be something like an array? And if so, how do I get original values ( strings ) out of it? Like this query should return 'IVAN'.
Thanks!
EDIT2 :
This ( c.getCount() ) still returns 0, i.e. no results... hmm... maybe then there's something with the helper?
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() ) );
The Cursor object returned by a query provides access to a recordset of results.
Once you have the Cursor, you have to iterate through it to get the values. In your case, you would do it like so --
if (cur.moveToFirst()) {
int placeColumn = cur.getColumnIndex("PLACE");
String place = cur.getString(placeColumn);
}
To get the NAME out based on a query by PLACE, you should do 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 */
);
A cursor is a pointer to the results set of your query. Read the Cursor documentation here: http://developer.android.com/reference/android/database/Cursor.html
Basically, you'll do something like:
String place;
if (c.moveToFirst){
place = c.getString( c.getColumnIndex("PLACE"));
}
精彩评论