標籤:版本 blog 讀寫 text null date database 關閉 state
SQLiteOpenHelper 類
SQLiteOpenHelper類是Android提供的用於操作SQLite資料庫的工具類,該工具類能方便地建立資料庫、表,以及管理資料庫版本。
常用方法
1、 synchronized SQLiteDatabase getReadableDatabase();
作用:以讀寫的方式開啟資料庫對應的SQLiteDatabase類的對象
2、 synchronized SQLiteDatabase getWriteableDatabase();
作用:以寫的方式建立或開啟庫對應的SQLiteDatabase類的對象
3、 abstract onCreate(SQLiteDatabase db);
作用:首次建立資料庫時調方法。
4、 abstract onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion);
作用:資料庫版本更新時調方法。
5、 synchronized void close();
作用:關閉所有開啟的SQLiteDatabase對象。
增、刪、改操作【定義MySQLiteOpenHelper】
1 public class MySQLiteOpenHelper extends SQLiteOpenHelper{ 2 /**重寫父類構造方法*/ 3 public MySQLiteOpenHelper(Context context) { 4 //建立指定資料庫:Activity對象,資料庫檔案名,遊標工廠,資料庫版本號碼 5 super(context,"person.db",null,1); 6 } 7 /**只在第一次建立資料庫時調用,資料庫只用在調用 8 getWritableDatabase 時候才會真正被調用 */ 9 public void onCreate(SQLiteDatabase db) {10 db.execSQL("create table if not exists person(" 11 +"pid integer primary key autoincrement,"12 +"name varchar(20),"+"phone varchar(12));");13 }14 /**修改表結構,資料庫版本更新時調用*/15 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {16 } 17 /**向資料庫插入資料*/18 public void insert(String sql,String [] args){19 //建立對象,以寫方式開啟資料庫20 SQLiteDatabase db=this.getWritableDatabase();21 db.execSQL(sql,args);22 }23 /**刪除資料庫中的資料*/24 public void delete(String sql,String [] args){25 SQLiteDatabase db=this.getWritableDatabase();26 db.execSQL(sql,args);27 }28 /**更新資料庫中的資料*/29 public void update(String sql,String [] args){ 30 SQLiteDatabase db=this.getWritableDatabase();31 db.execSQL(sql,args);32 }33 } MySQLiteOpenHelper類代碼
1 public class Main extends Activity implements OnClickListener{ 2 private Button save; //插入資料按鈕 3 private Button delete; //刪除資料按鈕 4 private Button update; //更新資料按鈕 5 public void onCreate(Bundle savedInstanceState) { 6 super.onCreate(savedInstanceState); 7 setContentView(R.layout.main); 8 save=(Button)findViewById(R.id.save); 9 delete=(Button)findViewById(R.id.delete);10 update=(Button)findViewById(R.id.update);11 save.setOnClickListener(this);12 delete.setOnClickListener(this);13 update.setOnClickListener(this);14 } 15 public void onClick(View v) {16 MySQLiteOpenHelper db=new MySQLiteOpenHelper(Main.this);17 switch(v.getId()){18 case R.id.save:19 db.insert("insert into person(name) values(?)",new String[]{"張飛"});20 Toast.makeText(this,"插入成功",3000).show();21 break;22 case R.id.delete:23 db.insert("delete from person where id=?",new String[]{"1"});24 Toast.makeText(this,"刪除成功",3000).show();25 break;26 case R.id.update:27 db.insert("update person set name=? where id=1",new String[]{"關羽"});28 Toast.makeText(this,"更新成功",3000).show();29 break;30 }31 }32 }Activity代碼
【安卓9】SQLiteOpenHelper 類、增刪改操作