// import略 public class DBHelper { private static final String[] COLS = new String[] { "_id","name"}; private SQLiteDatabase db; private final DBOpenHelper dbOpenHelper; public DBHelper(final Context context) { this.dbOpenHelper = new DBOpenHelper(context); establishDb(); } /** * 得到一個可寫的SQLite 資料庫,如果這個資料庫還沒有建立, * 那麼DBOpenHelper輔助類負責建立這個資料庫。 * 如果資料庫已經建立,那麼直接返回一個可寫的資料庫。 */ private void establishDb() { if (this.db == null) { this.db = this.dbOpenHelper.getWritableDatabase(); } } /** * 關閉資料庫 */ public void cleanup() { if (this.db != null) { this.db.close(); this.db = null; } } /** * 插入一條資料 */ public void insert(String id,String name) { ContentValues values = new ContentValues(); values.put("_id", id); values.put("name", id); this.db.insert(DBOpenHelper.TABLE_NAME, null, values); cleanup(); } /** * 更新一條資料 */ public void update(String id,String name) { ContentValues values = new ContentValues(); values.put("_id", id); values.put("name", id); this.db.update(DBOpenHelper.TABLE_NAME, values, "_id=" + id,null); cleanup(); } /** * 刪除一條資料 */ public void delete(final long id) { this.db.delete(DBOpenHelper.TABLE_NAME, "_id=" + id, null); } /** * 刪除所有資料 */ public void deleteAll() { this.db.delete(DBOpenHelper.TABLE_NAME, null, null); } private void query() { // 得到一個可寫的資料庫。 SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); // 進行資料庫查詢 Cursor cur = db.query(DBOpenHelper.TABLE_NAME, COLS, null, null, null, null, null); if(cur != null) { for(cur.moveToFirst();!cur.isAfterLast();cur.moveToNext()) { int idColumn = cur.getColumnIndex(COLS[0]); int nameColumn = cur.getColumnIndex(COLS[1]); String id = cur.getString(idColumn); String name = cur.getString(nameColumn); } cur.close(); } } } |