Android資料儲存方案
android內建資料庫——SQLLite
概述SQLite
SQLite是一款輕型的資料庫,是遵守ACID的關聯式資料庫管理系統,它的設計目標是嵌入 式的,而且目前已經在很多嵌入式產品中使用了它,它佔用資源非常的低,在嵌入式裝置中,可能只需要幾百K的記憶體就夠了。它能夠支援 Windows/Linux/Unix等等主流的作業系統,同時能夠跟很多程式語言相結合,比如Tcl、PHP、Java、C++、.Net等,還有ODBC介面,同樣比起 Mysql、PostgreSQL這兩款開源世界著名的資料庫管理系統來講,它的處理速度比他們都快。
建立資料庫
使用SQLiteOpenHepler來建立資料庫,首先明白SQLiteOpenHepler是一個抽象類,使用它就要建立自己的幫助類去繼承它。
當資料庫不可寫入的時候(磁碟空間已滿),getReadableDatabase()方法返回的物件將以只讀的方式開啟資料庫,而getWritableDatabase()將出現異常。
public class MyDatabaseHelper extends SQLiteOpenHelper { public static final String CREATE_BOOK = "create table Book (" + "id integer primary key autoincrement, " + "author text, " + "price real, " + "pages integer, " + "name text)"; public static final String CREATE_CATEGORY = "create table Category (" + "id integer primary key autoincrement, " + "category_name text, " + "category_code integer)"; }
對資料庫的操作
Android提供了建立和是用SQLite資料庫的API。SQLiteDatabase代表一個數據庫物件,提供了操作資料庫的一些方法。在Android的SDK目錄下有sqlite3工具,我們可以利用它建立資料庫、建立表和執行一些SQL語句。下面是SQLiteDatabase的常用方法。
SQLiteDatabase的常用方法 :增(insert)、刪(Delete)、改(Update)、查(Query)
方法名稱 |
方法表示含義 |
openOrCreateDatabase(String path,SQLiteDatabase.CursorFactory factory) |
開啟或建立資料庫 |
insert(String table,String nullColumnHack,ContentValues values) |
插入一條記錄 |
delete(String table,String whereClause,String[] whereArgs) |
刪除一條記錄 |
query(String table,String[] columns,String selection,String[] selectionArgs,String groupBy,String having,String orderBy) |
查詢一條記錄 |
update(String table,ContentValues values,String whereClause,String[] whereArgs) |
修改記錄 |
execSQL(String sql) |
執行一條SQL語句 |
close() |
關閉資料庫 |
每次進行以上操作時,都要建立自己定義繼承的幫助類。程式碼僅供參考
dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 2);//建立MyDatabaseHelper物件
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
// 開始組裝第一條資料
values.put("name", "The Da Vinci Code");
values.put("author", "Dan Brown");
values.put("pages", 454);
values.put("price", 16.96);
db.insert("Book", null, values); // 插入第一條資料
db.update("Book", values, "name = ?", new String[] { "The Da Vinci Code" });
db.delete("Book", "pages > ?", new String[] { "500" });
關於查詢操作,SQLlite有提供query方法,下面是query的引數
query引數多,但不用為每條語句指定所有的查詢語句,呼叫query()方法後會返回一個Cursor物件,查詢到的所有資料都將從這個物件中取出。
Cursor遊標常用方法
方法名稱 |
方法描述 |
getCount() |
獲得總的資料項數 |
isFirst() |
判斷是否第一條記錄 |
isLast() |
判斷是否最後一條記錄 |
moveToFirst() |
移動到第一條記錄 |
moveToLast() |
移動到最後一條記錄 |
move(int offset) |
移動到指定記錄 |
moveToNext() |
移動到下一條記錄 |
moveToPrevious() |
移動到上一條記錄 |
getColumnIndexOrThrow(String columnName) |
根據列名稱獲得列索引 |
getInt(int columnIndex) |
獲得指定列索引的int型別值 |
getString(int columnIndex) |
獲得指定列縮影的String型別值 |
使用SQL操作資料
具體用方法: