標籤:
SQLite簡介
Google為Andriod的較大的資料處理提供了SQLite,他在資料存放區、管理、維護等各方面都相當出色,功能也非常的強大。SQLite具備下列特點:
1.輕量級:使用 SQLite 只需要帶一個動態庫,就可以享受它的全部功能,而且那個動態庫的尺寸想當小。
2.獨立性:SQLite 資料庫的核心引擎不需要依賴第三方軟體,也不需要所謂的“安裝”。
3.隔離性:SQLite 資料庫中所有的資訊(比如表、視圖、觸發器等)都包含在一個檔案夾內,方便管理和維護。
4.跨平台:SQLite 目前支援大部分作業系統,不至電腦作業系統更在眾多的手機系統也是能夠運行,比如:Android。
5.多語言介面:SQLite 資料庫支援多語言編程介面。
6.安全性:SQLite 資料庫通過資料庫級上的獨佔性和共用鎖定來實現獨立交易處理。這意味著多個進程可以在同一時間從同一資料庫讀取資料,但只能有一個可以寫入資料。
Android為了讓我們能夠更好的管理資料庫,專門提供了一個SQLiteOpenHelper協助類,這是一個抽象類別,因此要使用的話需要建立一個自己的協助類去繼承它。SQLiteOpenHelper類中有兩個抽象方法,分別是onCreate(),和onUpgrade(),協助類中必須重寫這兩個方法,然後在這兩個方法中去實現建立、升級資料庫的邏輯。SQLiteOpenHelper中有兩個重要的執行個體方法,getWritableDatabase()和getReadableDatabase().這兩個方法都可以建立或開啟一個現有資料庫(如果資料庫已經存在,則直接開啟,否則建立一個新的資料庫),並返回一個資料庫的寫讀操作對象。不同的是當資料庫不可吸入的時候(如磁碟已滿)getReadableDatabase()的方法返回的對象將以唯讀方式開啟資料庫,而getWritableDatabase()則拋出異常。
SQLiteOpenHelper中有兩個構造方法可供重寫,一般使用參數較少的那一個,即public DatabaseHelper(Context context, String name, CursorFactory factory, int version),其中第一個參數是Context,必須有它才能對資料庫進行操作,第二個參數是資料庫的名字,第三個參數允許我們在查詢資料時返回一個Cursor,一般傳入為null,第四個參數是資料庫的版本號碼,可用於對資料庫的升級。通過代碼實現如下:
建立項目MySQLiteTest:在建立一個DatabaseHelper.java類,繼承SQLiteOpenHelper,同時修改activity_main.xml檔案,添加如下代碼:
<Button android:id="@+id/create_database" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="建立資料庫"/> <Button android:id="@+id/add_data" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/create_database" android:text="添加資料"/> <Button android:id="@+id/up_data" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/add_data" android:text="更新資料"/> <Button android:id="@+id/delete_data" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/up_data" android:text="刪除資料"/> <Button android:id="@+id/query_data" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/delete_data" android:text="查詢資料"/> <Button android:id="@+id/replace_data" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/query_data" android:text="使用事務替換資料"/>
activity_main.xml
在DatabaseHelper.java類中 建立一張Book表
public class DatabaseHelper extends SQLiteOpenHelper { public static final String CREATE_BOOK="create table Book(" +"id integer primary key autoincrement," +"author text," +"price real," +"page integer," +"name text)"; private Context myContext; public DatabaseHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); // TODO Auto-generated constructor stub myContext=context; } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub db.execSQL(CREATE_BOOK); Toast.makeText(myContext, "Create Success", Toast.LENGTH_SHORT).show(); } @Override public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) { // TODO Auto-generated method stub }}DatabaseHelper
這裡把建表的語句定義成一個字串常量,然後在onCreate()方法中調用SQLiteDatabase的execSQL()方法來執行這條語句,並彈出“Create Success”,這樣即可以保證在資料庫建立完成的同時建立Book表。
然後在MainActivity.java中點擊建立資料庫的按鈕,代碼為:
定義一些變數:
private Button CreatBsesBtn;//建立資料庫 private Button addDataBtn;//添加資料 private Button udDataBtn;//更新資料 private Button deleteDataBtn;//刪除資料 private Button queryDataBtn;//插敘資料 private Button replaceDataBtn;//替換資料 private DatabaseHelper mydb;
button
mydb=new DatabaseHelper(this, "BookStore.db", null, 1); //添加資料庫 CreatBsesBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub mydb.getWritableDatabase(); } });添加資料庫
這裡通過構建一個DatabaseHelper,並通過建構函式的參數將資料庫的名字指定為BookStore.db,版本號碼為1,然後在點擊事件中調用getWritableDatabase()方法。這裡查看不具體說明,可以用adb shell來對資料庫和表的建立情況進行檢查,具體配置不在說明。
下面不具體說明,看代碼:
添加資料:
//添加資料 addDataBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub SQLiteDatabase db=mydb.getWritableDatabase(); ContentValues cv=new ContentValues(); //添加資料 cv.put("name", "Android"); cv.put("author", "jesson"); cv.put("page", 120); cv.put("price", 75.0); db.insert("Book", null, cv); cv.clear(); db.insert("Book",null, cv); } }); addData
在這個事件裡,先擷取到SQLiteDatabase對象,然後使用ContentValues來對要添加的資料進行組裝,因為id那一列設定的是自動成長,因此這裡只需四列就行了。最後調用insert()方法進行資料插入。
更新資料:
//更新資料 udDataBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub SQLiteDatabase db=mydb.getWritableDatabase(); ContentValues cv=new ContentValues(); cv.put("prices", 18.32); db.update("Book", cv, "name=?", new String[]{"Android"}); } });更新資料
這裡使用update()方法去執行具體更新操作,使用第三四個參數來指定具體更新的是哪一行的,也就是:將書名為Android的書本價格改為 18.32(原來是75.0)。
刪除資料:
//刪除資料 deleteDataBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub SQLiteDatabase db=mydb.getWritableDatabase(); db.delete("Book", "page>?", new String[]{"500"}); } });刪除資料:
這裡使用delete()方法去執行刪除操作,使用第二三個參數來指定具體刪除的是哪一行,這裡刪除頁數超過50頁的書。
//查詢操作 queryDataBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub SQLiteDatabase db=mydb.getWritableDatabase(); //查詢表中所有資料 Cursor cursor=db.query("Book", null, null, null, null, null, null); if(cursor.moveToFirst()){ do{ String name=cursor.getString(cursor.getColumnIndex("name")); String author=cursor.getString(cursor.getColumnIndex("author")); int page=cursor.getInt(cursor.getColumnIndex("page")); double price=cursor.getDouble(cursor.getColumnIndex("price")); }while(cursor.moveToNext()); } cursor.close(); } });查詢操作
SQLiteDatabase中提供一個query()方法對資料進行查詢,這個方法比較複雜,最短有七個參數,分別如下表所示:
| query()方法參數 |
描述 |
| table |
指定查詢的表名(可為null) |
| columns |
指定查詢的列名(可為null) |
| selection |
指定where的約束條件(可為null) |
| selectionArgs |
為where中的預留位置提供具體的值(可為null) |
| groupBy |
指定需要group by的列(可為null) |
| having |
對group by後的結果進一步約束(可為null) |
| orderBy |
指定查詢結果的排序方式(可為null) |
調用query()方法後會返回一個Cursor對象,查詢到的所有資料都將從這個對象中取出。在本次查詢中,我們在得到Cursor對象後,調用它的moveToFirst()方法將資料的指標移動到第一行的位置,然後進入一個迴圈當中,去遍曆查詢到的每一行資料。在這個迴圈中,可以通過getColumnIndex()方法擷取到每一列在表中對應的位置索引。最後別忘了關閉Cursor.
事務的使用,在下一篇裡進行介紹。
安卓資料存放區(3):SQLite資料庫儲存