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

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

詳細(xì)代碼:github.com/Baolvlv/LearnAndroid/tree/master/UsingSqlite

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

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

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為版本號(hào)

publicDb(Context context) {

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

}

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

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

@Override

public voidonCreate(SQLiteDatabase db) {

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

db.execSQL("CREATE TABLE user("+

"_id INTEGER PRIMARY KEY AUTOINCREMENT,"+

"name TEXT,"+

"sex TEXT)");

}

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

@Override

public voidonUpgrade(SQLiteDatabase db, intoldVersion, intnewVersion) {

}

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

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

Db db =newDb(this);

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

SQLiteDatabase dbWrite = db.getWritableDatabase();

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

ContentValues cv =newContentValues();

//輸入對(duì)應(yīng)的鍵值對(duì)的值

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

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

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

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

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

//使用完之后關(guān)閉數(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獲取查詢列的編號(hào)

通過getString獲取編號(hào)下的值

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對(duì)象用于接收查詢結(jié)果Cursor

privateSimpleCursorAdapteradapter;

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

db=newDb(this);

dbRead=db.getReadableDatabase();

dbWrite=db.getWritableDatabase();

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

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

adapter=newSimpleCursorAdapter(this,R.layout.user_list_cell

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

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

大小文本的樣式分別為:

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

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

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

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

db.execSQL("CREATE TABLE user("+

"_id INTEGER PRIMARY KEY AUTOINCREMENT,"+

"name TEXT DEFAULT\"\","+

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

實(shí)例化ListView并為listview設(shè)置adapter

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

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

lv.setAdapter(adapter);

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

//更改adapter的Cursor,從而達(dá)到更新列表項(xiàng)

private voidrefershListview(){

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

adapter.changeCursor(c);

}

執(zhí)行refershListView后,adapter改變,setAdapter自動(dòng)執(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();

}

實(shí)現(xiàn)ListView長(zhǎng)按刪除item

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

lv.setOnItemLongClickListener(newAdapterView.OnItemLongClickListener() {

@Override

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

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

return true;

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

newAlertDialog.Builder(MainActivity.this).setTitle("提醒").setMessage("你確定要?jiǎng)h除該項(xiàng)嗎?")

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

通過adapter中的cursor移動(dòng)到相應(yīng)位置,通過dbWriter刪除,刪除后刷新列表

//通過adapter獲取到Cursor,并移動(dòng)到長(zhǎng)按的位置

Cursor c =adapter.getCursor();

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

c.moveToPosition(position);

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

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

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

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

refershListview();

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容