標籤:
使用過 SQLite 資料庫的童鞋對 Cursor 應該不陌生,如果你是搞.net 開發你大可以把Cursor理解成 Ado.net 中的資料集合相當於dataReader。今天特地將它單獨拿出來談,加深自己和大家對Android 中使用 Cursor 的理解。
關於 Cursor
在你理解和使用 Android Cursor 的時候你必須Crowdsourced Security Testing道關於 Cursor 的幾件事情:
Cursor 是每行的集合。
使用 moveToFirst() 定位第一行。
使用moveToNext()定位到下一行,返回布爾類型
你必須知道每一列的名稱。
你必須知道每一列的資料類型。
Cursor 是一個隨機的資料來源。
所有的資料都是通過下標取得。
樣本:
query()方法實際上是把select語句拆分成了若干個組成部分,然後作為方法的輸入參數:
SQLiteDatabase db = databaseHelper.getWritableDatabase(); Cursor cursor = db.query("person", new String[]{"personid,name,age"}, "name like ?", new String[]{"%傳智%"}, null, null, "personid desc", "1,2"); String columnNmaes[] = cursor.getColumnNames(); String columnName; String name; int personid; int age; while (cursor.moveToNext()) { for (int i = 0; i < columnNmaes.length; i++) { columnName = columnNmaes[i]; if (columnName==“編號”) personid=cursor.getInt(i); if (columnName==“姓名”) name=cursor.getInt(i); if (columnName==“年齡”) age=cursor.getInt(i); } } cursor.close(); db.close();
Android 開發筆記 “Sqlite Cursor 使用”