Android SQLiteOpenHelper SQLite数据库增删改查操作

  1. import android.content.ContentValues;  
  2. import android.content.Context;  
  3. import android.database.Cursor;  
  4. import android.database.sqlite.SQLiteDatabase;  
  5. import android.database.sqlite.SQLiteOpenHelper;  
  6.  
  7. public class ToDoDB extends SQLiteOpenHelper {  
  8.     private final static String DATABASE_NAME = "todo_db";  
  9.     private final static int DATABASE_VERSION = 1;  
  10.     private final static String TABLE_NAME = "todo_table";  
  11.     public final static String FIELD_id = "_id";  
  12.     public final static String FIELD_TEXT = "todo_text";  
  13.  
  14.     public ToDoDB(Context context) {  
  15.         super(context, DATABASE_NAME, null, DATABASE_VERSION);  
  16.     }  
  17.  
  18.     @Override 
  19.     public void onCreate(SQLiteDatabase db) {  
  20.         /* 建立table */ 
  21.         String sql = "CREATE TABLE " + TABLE_NAME + " (" + FIELD_id  
  22.                 + " INTEGER primary key autoincrement, " + " " + FIELD_TEXT  
  23.                 + " text)";  
  24.         db.execSQL(sql);  
  25.     }  
  26.  
  27.     @Override 
  28.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  29.         String sql = "DROP TABLE IF EXISTS " + TABLE_NAME;  
  30.         db.execSQL(sql);  
  31.         onCreate(db);  
  32.     }  
  33.  
  34.     public Cursor select() {  
  35.         SQLiteDatabase db = this.getReadableDatabase();  
  36.         Cursor cursor = db  
  37.                 .query(TABLE_NAME, nullnullnullnullnullnull);  
  38.         return cursor;  
  39.     }  
  40.  
  41.     public long insert(String text) {  
  42.         SQLiteDatabase db = this.getWritableDatabase();  
  43.         /* 将新增的值放入ContentValues */ 
  44.         ContentValues cv = new ContentValues();  
  45.         cv.put(FIELD_TEXT, text);  
  46.         long row = db.insert(TABLE_NAME, null, cv);  
  47.         return row;  
  48.     }  
  49.  
  50.     public void delete(int id) {  
  51.         SQLiteDatabase db = this.getWritableDatabase();  
  52.         String where = FIELD_id + " = ?";  
  53.         String[] whereValue = { Integer.toString(id) };  
  54.         db.delete(TABLE_NAME, where, whereValue);  
  55.     }  
  56.  
  57.     public void update(int id, String text) {  
  58.         SQLiteDatabase db = this.getWritableDatabase();  
  59.         String where = FIELD_id + " = ?";  
  60.         String[] whereValue = { Integer.toString(id) };  
  61.         /* 将修改的值放入ContentValues */ 
  62.         ContentValues cv = new ContentValues();  
  63.         cv.put(FIELD_TEXT, text);  
  64.         db.update(TABLE_NAME, cv, where, whereValue);  
  65.     }