Android中Sqlite數(shù)據(jù)庫讀寫數(shù)據(jù)

? ? ? ? Sqlite數(shù)據(jù)庫作為一個輕量級數(shù)據(jù)庫,可以較為方便地實現(xiàn)Android中諸如歷史記錄的儲存等操作。本文首先介紹Sqlite數(shù)據(jù)庫的創(chuàng)建與讀寫等數(shù)據(jù)庫操作,而后完成使用界面的方式操作Sqlite數(shù)據(jù)庫中的數(shù)據(jù)。

詳細代碼:github.com/Baolvlv/LearnAndroid/tree/master/UsingSqlite

一、Sqlite數(shù)據(jù)庫的數(shù)據(jù)讀取與寫入

SQLite是一個進程內(nèi)的庫,實現(xiàn)了自給自足的、無服務器的、零配置的、事務性的SQL數(shù)據(jù)庫引擎。它是一個零配置的數(shù)據(jù)庫,不需要在系統(tǒng)中配置。SQLite引擎不是一個獨立的進程,可以按應用程序需求進行靜態(tài)或動態(tài)連接。SQLite直接訪問其存儲文件。

1.創(chuàng)建

創(chuàng)建類繼承自SQLiteOpenHelper

public classDbextendsSQLiteOpenHelper {

添加構(gòu)造函數(shù),不需要的參數(shù)可以不寫

//構(gòu)造函數(shù),參數(shù):name為數(shù)據(jù)庫名稱,Cursor用于逐行讀取數(shù)據(jù)庫結(jié)果,封裝的查詢結(jié)果,version為版本號

publicDb(Context context) {

super(context,"db", null,1);

}

重寫數(shù)據(jù)庫創(chuàng)建與升級方法

//當應用中不存在數(shù)據(jù)庫時創(chuàng)建

@Override

public voidonCreate(SQLiteDatabase db) {

//創(chuàng)建表,包含name,sex兩列,文本類型,默認值為空? PRIMARY KEY AUTOINCREMENT主鍵自增

db.execSQL("CREATE TABLE user("+

"_id INTEGER PRIMARY KEY AUTOINCREMENT,"+

"name TEXT,"+

"sex TEXT)");

}

//數(shù)據(jù)庫升級,sql語句操作數(shù)據(jù)庫,檢查操作系統(tǒng)中的同名數(shù)據(jù)庫版本號低則升級

@Override

public voidonUpgrade(SQLiteDatabase db, intoldVersion, intnewVersion) {

}

2.寫入數(shù)據(jù)

//實例化數(shù)據(jù)庫對象

Db db =newDb(this);

//獲取可寫入數(shù)據(jù)庫用于插入數(shù)據(jù)

SQLiteDatabase dbWrite = db.getWritableDatabase();

//使用ContentValues封裝數(shù)據(jù)

ContentValues cv =newContentValues();

//輸入對應的鍵值對的值

cv.put("name","bss");

cv.put("sex","男");

//插入數(shù)據(jù),參數(shù)為表名,當列為空時的填充值,封裝數(shù)據(jù)的ContentValue

dbWrite.insert("user",null,cv);

使用完成后關閉數(shù)據(jù)庫

//使用完之后關閉數(shù)據(jù)庫

dbWrite.close();

3.讀取數(shù)據(jù)

獲取可讀取數(shù)據(jù)庫

SQLiteDatabasedbRead = db.getReadableDatabase();

使用query()方法查詢,返回值為Cursor

Cursor c = dbRead.query("user",null,null,null,null,null,null);

query()的參數(shù)為:

參數(shù):表名,查詢的列,查詢條件,條件參數(shù),分組,分組條件,順序

查詢列的寫法:

new String[]{"name"}

為防止sql注入攻擊,查詢條件與條件參數(shù)為:

"name =?",new String[]{"bss"

通過Cursor的moveToNext方法判斷結(jié)果是否結(jié)束,通過getColumnIndex獲取查詢列的編號

通過getString獲取編號下的值

while(c.moveToNext()){

String name = c.getString(c.getColumnIndex("name"));

String sex = c.getString(c.getColumnIndex("sex”));

二、通過界面操作Sqlite數(shù)據(jù)庫

將數(shù)據(jù)庫查詢結(jié)果呈現(xiàn)到ListView中

主布局中添加listView,聲明SimpleCursorAdapter對象用于接收查詢結(jié)果Cursor

privateSimpleCursorAdapteradapter;

實例化數(shù)據(jù)庫對象,獲取可讀寫數(shù)據(jù)庫對象

db=newDb(this);

dbRead=db.getReadableDatabase();

dbWrite=db.getWritableDatabase();

實例化SimpleCursorAdapter對象,參數(shù)為

//參數(shù):context,顯示結(jié)果的布局資源,Cursor,Cursor的需要輸出的數(shù)據(jù)源,輸出的位置,初次查詢時cursor可以為空

adapter=newSimpleCursorAdapter(this,R.layout.user_list_cell

,null,newString[]{"name","sex"},new int[]{R.id.tvName,R.id.tvSex});

用于呈現(xiàn)結(jié)果的布局需要手動創(chuàng)建,線形布局,分別用大小文本呈現(xiàn)

大小文本的樣式分別為:

android:textAppearance="?android:textAppearanceLarge”/>

android:textAppearance="?android:textAppearanceMedium"/>

注意:SimpleCursorAdapter要求數(shù)據(jù)表中必須有_id這一列,且為自增主鍵,創(chuàng)建如下:

//創(chuàng)建表,包含name,sex兩列,文本類型,默認值為空? PRIMARY KEY AUTOINCREMENT主鍵自增

db.execSQL("CREATE TABLE user("+

"_id INTEGER PRIMARY KEY AUTOINCREMENT,"+

"name TEXT DEFAULT\"\","+

"sex TEXT DEFAULT\"\")");

實例化ListView并為listview設置adapter

lv= (ListView) findViewById(R.id.list);

//只要adapter發(fā)生改變,setAdapter()函數(shù)就執(zhí)行

lv.setAdapter(adapter);

設置刷新列表的函數(shù),通過改變adapter的cursor從而改變adapter達到刷新列表的目的

//更改adapter的Cursor,從而達到更新列表項

private voidrefershListview(){

Cursor c =dbRead.query("user",null,null,null,null,null,null);

adapter.changeCursor(c);

}

執(zhí)行refershListView后,adapter改變,setAdapter自動執(zhí)行,列表刷新

在button的onClick函數(shù)中,通過ContentValue存入數(shù)據(jù),通過dbwriter將數(shù)據(jù)插入數(shù)據(jù)庫

插入完成后刷新列表

public voidonClick(View v) {

ContentValues cv =newContentValues();

cv.put("name",etName.getText().toString());

cv.put("sex",etSex.getText().toString());

dbWrite.insert("user",null,cv);

refershListview();

}

實現(xiàn)ListView長按刪除item

為listView設置onItemLongClickListener,返回值改為true,提示系統(tǒng)此次為長按操作,可以繼續(xù)執(zhí)行后續(xù)操作

lv.setOnItemLongClickListener(newAdapterView.OnItemLongClickListener() {

@Override

public booleanonItemLongClick(AdapterView parent,View view, final intposition, longid) {

//反饋操作系統(tǒng)此次是否為長按,true為長按,可觸發(fā)震動等

return true;

通過AlertDialog創(chuàng)建對話框,設置title與message,通過積極按鈕(positive Button)設置需要操作的button,銅過消極按鈕(negative Button)設置不需要操作的button,positive?button需要設置DialogInterface.onClickListener,negative button的事件監(jiān)聽器為null,通過show彈出對話框。

newAlertDialog.Builder(MainActivity.this).setTitle("提醒").setMessage("你確定要刪除該項嗎?")

.setPositiveButton("確定", newDialogInterface.OnClickListener() {

通過adapter中的cursor移動到相應位置,通過dbWriter刪除,刪除后刷新列表

//通過adapter獲取到Cursor,并移動到長按的位置

Cursor c =adapter.getCursor();

//內(nèi)部類訪問可變變量有問題

c.moveToPosition(position);

//獲取數(shù)據(jù)庫中這條數(shù)據(jù)的_id

intitemId = c.getInt(c.getColumnIndex("_id"));

//刪除對應的數(shù)據(jù),參數(shù)為表名,刪除的條件,條件的結(jié)果

dbWrite.delete("user","_id=?",newString[]{itemId+""});

refershListview();

注意:數(shù)據(jù)庫創(chuàng)建時的onCreate函數(shù)在沒有數(shù)據(jù)庫時才會創(chuàng)建,如需重新創(chuàng)建應先手動清除應用數(shù)據(jù)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容