建立Database

SQLiteDatabase db = openOrCreateDatabase("mydb.db",MODE_PRIVATE,null);
第二個參數可以用
MODE_PRIVATE
MODE_WORLD_READABLE
MODE_WORLD_WRITEABLE

刪除Database

deleteDatabase("mydb.db");

執行SQL指令的方法如下

execSQL() 直接執行SQL指令,包含新增,修改,刪除及table的建立
rawQuery() 查詢所有的資料
insert() 以ContentValues的方式透過insert()新增資料
delete() 刪除資料
update) 以ContentValuses的方式透過update()修改資料
query() 查詢指定的資料
close() 關閉資料庫

execSQL()的使用

SQLiteDatabase db = openOrCreateDatabase("db1.db",MODE_PRIVATE,null);
//建立table
String sqlstr = "create table mytable(_id interger primary key, name text, phone text)";
db.execSQL(sqlstr);
//新增資料
String sqlstr = "insert into mytable(_id,name,phone) values(001,'Charles','04-12345678')";
db.execSQL(sqlstr);
//修改資料
String sqlstr = "update mytable set _id=0001 where _id=001";
db.execSQL(sqlstr);
//刪除資料
String sqlstr = "delete from mytable where _id=0001";
db.execSQL(sqlstr);
//刪除table
String sqlstr = "drop table mytable";
db.execSQL(sqlstr);

當你用完資料庫時,記得將資料庫連結清掉

@Override
protected void onDestroy(){
    super.onDestroy();
    db.close();
}

rawQuery()的使用

Cursor cursor = db.rawQuery("select * from mytable",null);

query()的用法

query()所帶的參數依序分別是 1.String table 2.String[] colums 3.String selection 4.String[] selectionsArg 5.Strint groupBy 6.String having 7.String orderBy 8.String limit

Cursor cursor = db.query("mytable", new String[]{"_id", "name", "phone"}, null, null, null, null, null, null);

insert()的用法

ContentValues cv = new ContentValues();
cv.put("_id", 0002);
cv.put("name", "jash");
cv.put("phone", "04-23456789");
db.insert("mytable", null, cv);

update()的用法

ContentValues cv = new ContentValues();
cv.put("name", "JashLiao");
cv.put("phone", "02-23456789");
db.update("mytable", cv, "_id=0002", null);

delete()的用法

db.delete("mytable", "_id=0002", null);




arrow
arrow
    文章標籤
    android sqlite usage
    全站熱搜

    痞客興 發表在 痞客邦 留言(0) 人氣()