Android的數(shù)據(jù)存儲(下)
一、Android數(shù)據(jù)庫使用
Android中使用android.database.sqlite.SQLiteDatabase來表示一個數(shù)據(jù)庫對象,它提供了兩種模式來幫助開發(fā)者進(jìn)行增刪改查等基本數(shù)據(jù)庫操作。
利用SQL語句描述操作
利用SQL語句調(diào)用SQLiteDatabase.execSql或SQLiteDatabase.rawQuery來執(zhí)行操作。
- //利用sql查詢數(shù)據(jù)
- Cursor data = db.rawQuery("select id,name from table");
- //利用sql插入數(shù)據(jù)
- db.execSql("insert into contacts (id,name) values (2,'cpacm')");
稍微學(xué)過sql語句的人應(yīng)該都看的懂上面的代碼(其實看語句的意思也能知道個大概~)
在 這里我來解釋一下Cursor(游標(biāo))的作用吧,游標(biāo)不能顧名思義(up主當(dāng)時學(xué)習(xí)數(shù)據(jù)庫時一度將游標(biāo)當(dāng)做與C語言里面的指針變量一樣,雖然有點對,但意 思還是理解錯了),Cursor它是系統(tǒng)為用戶開設(shè)的一個數(shù)據(jù)緩沖區(qū),是的,它是一塊數(shù)據(jù)區(qū)域,存放SQL語句的執(zhí)行結(jié)果。但是它也提供了能從包括多條數(shù) 據(jù)記錄的結(jié)果集中每次提取一條記錄的機制,這一點也跟指針很像。游標(biāo)總是與一條SQL選擇語句相關(guān)聯(lián)因為游標(biāo)由結(jié)果集(可以是零條、一條或由相關(guān)的選擇語 句檢索出的多條記錄)和結(jié)果集中指向特定記錄的游標(biāo)位置組成。當(dāng)決定對結(jié)果集進(jìn)行處理 時,必須聲明一個指向該結(jié)果集的游標(biāo)。用C語言作比較的話,如果寫過對文件進(jìn)行處理的程序,那么游標(biāo)就像您打開文件所得到的文件句柄一樣,只要文件打開成 功,該文件句柄就可代表該文件??傊涀?,游標(biāo)是一塊有著特有記號的一塊數(shù)據(jù)區(qū)域,能夠讓用戶逐條從中讀取出數(shù)據(jù)。
結(jié)構(gòu)化的方式描述數(shù)據(jù)庫的操作
這樣即使我們不熟悉SQL語句,也能使用最熟悉的面向?qū)ο蟮姆绞竭M(jìn)行數(shù)據(jù)庫操作。
- //結(jié)構(gòu)化的方式查詢數(shù)據(jù)
- Cursor data = db.query("contacts",new String[]{"id","name"},null,null,null,null,null);
- //結(jié)構(gòu)化方式插入數(shù)據(jù)
- ContentValue values = new ContentValues();
- values.put("id",2);
- values.put("name","cpacm");
- db.insert("table",null,values);
- /**
- * 參數(shù)說明
- * table:數(shù)據(jù)表名,columns:需要顯示的列名,如果為null則相當(dāng)與*
- * selection:相當(dāng)于sql語句的where條件;selectionArgs數(shù)組放的是where條件要替換的?號
- * groupBy:SQL語句的Group, orderBy: 排序,默認(rèn)asc
- **/
- public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy){
- }
比如說我要查詢的SQL語句為
SELECT CustomerName, SUM(OrderPrice) FROM Orders WHERE Country=? GROUP BY CustomerName HAVING SUM(OrderPrice)>500 ORDER BY CustomerName
那么我寫的代碼如下
- //數(shù)據(jù)表名
- String table = "Orders" ;
- //要顯示的列名
- String[] columns = new String[] { "CustomerName" , "SUM(OrderPrice)" };
- //選擇條件
- String selection = "Country=?" ;
- //里面的變量對應(yīng)條件中的問號,多個的時候請一一入座。
- String[] selectionArgs = new String[]{ "China" };
- //分組名
- String groupBy = "CustomerName" ;
- //分組的條件
- String having = "SUM(OrderPrice)>500" ;
- //按字段排序
- String orderBy = "CustomerName" ;
- Cursor c = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);
這樣就能實現(xiàn)數(shù)據(jù)庫的查詢了。其它的語句參數(shù)都是差不多的,這里就不一一介紹了。
public long insert (String table, String nullColumnHack, ContentValues values)
public int delete(String table, String whereClause, String[] whereArgs)
public int update(String table, ContentValues values, String whereClause, String[] whereArgs)
課外小知識:關(guān)于GroupBy和Having的使用
group by 顧名思義就是按照xxx進(jìn)行分組,它必須有“聚合函數(shù)”來配合才能使用,使用時至少需要一個分組標(biāo)識字段。聚合函數(shù)有:sum()、count()、 avg()等,使用group by目的就是要將數(shù)據(jù)分組進(jìn)行匯總操作。比如上面sql語句的CustomerName,如果它有四個行{“張三”,“李四”,“張三”,“李四”},那 么此時就會分成兩組,分別為張三組和李四組,然后統(tǒng)計出他們使用的orderprice總和。
HAVING作用就是為每一個組指定條件,像 where指定條件一樣,也就是說,可以根據(jù)你指定的條件來選擇行。如果你要使用HAVING子句的話,它必須處在GROUP BY子句之后。還是上面的SQL語句,如果張三的SUM(OrderPrice)沒有超過500,那么張三組就不會顯示。
SQL語句的預(yù)編譯
在實踐中,有的SQL語句需要被反復(fù)使用,為了避免反復(fù)解析SQL語句產(chǎn)生的開銷,可以對需要復(fù)用的SQL語句進(jìn)行預(yù)編譯,來提高數(shù)據(jù)庫操作的執(zhí)行效率。
//編譯復(fù)雜的SQL語句 SQLiteStatement compiledSql = db.compileStatement(aSQL); //執(zhí)行SQL compiledSql.execute();
- //編譯復(fù)雜的SQL語句
- SQLiteStatement compiledSql = db.compileStatement(aSQL);
- //執(zhí)行SQL
- compiledSql.execute();
課外小知識:所謂事務(wù)是用戶定義的一 個數(shù)據(jù)庫操作序列,這些操作要么全做要么全不做,是一個不可分割的工作單位。例如,在關(guān)系數(shù)據(jù)庫中,一個事務(wù)可以是一條SQL語句、一組SQL語句或整個 程序。 簡單舉個例子就是你要同時修改數(shù)據(jù)庫中兩個不同表的時候,如果它們不是一個事務(wù)的話,當(dāng)***個表修改完,可是第二表改修出現(xiàn)了異常而沒能修改的情況下,就 只有第二個表回到未修改之前的狀態(tài),而***個表已經(jīng)被修改完畢。 而當(dāng)你把它們設(shè)定為一個事務(wù)的時候,當(dāng)***個表修改完,可是第二表改修出現(xiàn)了異常而沒能修改的情況下,***個表和第二個表都要回到未修改的狀態(tài)!這就是所 謂的事務(wù)回滾。
SQLiteOpenHelper
在SQLiteOpenHelper中,封裝了一個SqliteDatabase對象,使用著可以通過使用此類來進(jìn)行數(shù)據(jù)庫的操作。
- package com.example.notebook;
- import android.content.Context;
- import android.database.sqlite.SQLiteDatabase;
- import android.database.sqlite.SQLiteOpenHelper;
- import android.database.sqlite.SQLiteDatabase.CursorFactory;
- public class DBHelper extends SQLiteOpenHelper{
- private static final int VERSION=1;
- /**
- * 在SQLiteOpenHelper的子類當(dāng)中,必須有該構(gòu)造函數(shù)
- * @param context 上下文對象
- * @param name 數(shù)據(jù)庫名稱
- * @param factory
- * @param version 當(dāng)前數(shù)據(jù)庫的版本,值必須是整數(shù)并且是遞增的狀態(tài)
- */
- public DBHelper(Context context,String name,CursorFactory factory,int version){
- super(context,name,factory,version);
- }
- public DBHelper(Context context, String name, int version){
- this(context,name,null,version);
- }
- public DBHelper(Context context, String name){
- this(context,name,VERSION);
- }
- @Override
- public void onCreate(SQLiteDatabase db) {
- // 數(shù)據(jù)庫***構(gòu)造時,會調(diào)用該函數(shù),可以在這里構(gòu)造表、索引,等等
- System.out.println("create a database");
- //execSQL用于執(zhí)行SQL語句
- db.execSQL("create table notebook(_id integer primary key autoincrement,pic varchar(50),title varchar(20),content text,time varchar)");
- }
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
- // 如果給定的當(dāng)前數(shù)據(jù)庫版本高于已有數(shù)據(jù)庫版本,調(diào)用該函數(shù)
- System.out.println("upgrade a database");
- }
- }
SQLiteOpenHelper的應(yīng)用
新建一個數(shù)據(jù)庫管理類DBManager
- package com.example.notebook;
- import android.content.ContentValues;
- import android.content.Context;
- import android.database.Cursor;
- import android.database.sqlite.SQLiteDatabase;
- import android.database.sqlite.SQLiteException;
- import android.util.Log;
- public class DBManager {
- private Context mContext = null;
- private SQLiteDatabase mSQLiteDatabase = null;//用于操作數(shù)據(jù)庫的對象
- private DBHelper dh = null;//用于創(chuàng)建數(shù)據(jù)庫的對象
- private String dbName = "note.db";//數(shù)據(jù)庫的名稱
- private int dbVersion = 1;//數(shù)據(jù)庫的版本
- public DBManager(Context context){
- mContext = context;
- }
- public void open(){
- try{
- dh = new DBHelper(mContext, dbName, null, dbVersion);//建立數(shù)據(jù)庫
- if(dh == null){
- Log.v("msg", "is null");
- return ;
- }
- mSQLiteDatabase = dh.getWritableDatabase();//以可寫方式打開數(shù)據(jù)庫
- //dh.onOpen(mSQLiteDatabase);
- }catch(SQLiteException se){
- se.printStackTrace();
- }
- }
- public void close(){
- mSQLiteDatabase.close();//關(guān)閉數(shù)據(jù)庫
- dh.close();
- }
- public Cursor selectAll(){
- Cursor cursor = null;
- try{
- //sql語句操作
- String sql = "select * from notebook";
- cursor = mSQLiteDatabase.rawQuery(sql, null);
- }catch(Exception ex){
- ex.printStackTrace();
- cursor = null;
- }
- return cursor;
- }
- public Cursor selectById(int id){
- //String result[] = {};
- Cursor cursor = null;
- try{
- //sql語句操作
- String sql = "select * from notebook where _id='" + id +"'";
- cursor = mSQLiteDatabase.rawQuery(sql, null);
- }catch(Exception ex){
- ex.printStackTrace();
- cursor = null;
- }
- return cursor;
- }
- public long insert(String title, String content,String pic){
- long datetime = System.currentTimeMillis();
- long l = -1;
- try{
- //結(jié)構(gòu)化方式操作
- ContentValues cv = new ContentValues();
- cv.put("title", title);
- cv.put("content", content);
- cv.put("time", datetime);
- cv.put("pic", pic);
- l = mSQLiteDatabase.insert("notebook", null, cv);
- // Log.v("datetime", datetime+""+l);
- }catch(Exception ex){
- ex.printStackTrace();
- l = -1;
- }
- return l;
- }
- public int delete(int id){
- int affect = 0;
- try{
- //結(jié)構(gòu)化方式操作
- affect = mSQLiteDatabase.delete("notebook", "_id=?", new String[]{String.valueOf(id)});
- }catch(Exception ex){
- ex.printStackTrace();
- affect = -1;
- }
- return affect;
- }
- public int update(int id, String title, String content,String pic){
- int affect = 0;
- try{
- //結(jié)構(gòu)化方式操作
- ContentValues cv = new ContentValues();
- cv.put("title", title);
- cv.put("content", content);
- cv.put("pic", pic);
- String w[] = {String.valueOf(id)};
- affect = mSQLiteDatabase.update("notebook", cv, "_id=?", w);
- }catch(Exception ex){
- ex.printStackTrace();
- affect = -1;
- }
- return affect;
- }
- }
獲取數(shù)據(jù)示例
- private DBManager dm = null;// 數(shù)據(jù)庫管理對象
- rivate Cursor cursor = null;
- dm = new DBManager(this);//數(shù)據(jù)庫操作對象
- dm.open();//打開數(shù)據(jù)庫操作對象
- cursor = dm.selectAll();//獲取所有數(shù)據(jù)
- cursor.moveToFirst();//將游標(biāo)移動到***條數(shù)據(jù),使用前必須調(diào)用
- int count = cursor.getCount();//個數(shù)
- ArrayList<String> contents = new ArrayList<String>();//圖片的所有集合
- ArrayList<String> imgs = new ArrayList<String>();//圖片的所有集合
- ArrayList<String> items = new ArrayList<String>();//標(biāo)題的所有集合
- ArrayList<String> times = new ArrayList<String>();//時間的所有集合
- for(int i= 0; i < count; i++){
- contents.add(cursor.getString(cursor.getColumnIndex("content")));
- imgs.add(cursor.getString(cursor.getColumnIndex("pic")));
- items.add(cursor.getString(cursor.getColumnIndex("title")));
- times.add(cursor.getString(cursor.getColumnIndex("time")));
- //cursor.getInt(cursor.getColumnIndex("_id"))
- cursor.moveToNext();//將游標(biāo)指向下一個
- }
- dm.close();//關(guān)閉數(shù)據(jù)操作對象
數(shù)據(jù)庫的并發(fā)問題
并發(fā)問題是使用數(shù)據(jù)庫過程中最容易碰到的問題,如果在開發(fā)中碰到了android.database.SQLException異常,并提示"database is locked",那很有可能是出現(xiàn)了數(shù)據(jù)庫的死鎖導(dǎo)致無法訪問。原因是Sqlite會對文件的讀寫進(jìn)行加鎖,防止數(shù)據(jù)被破壞。而在Android框架層SqliteDatabase會對所有數(shù)據(jù)庫對象進(jìn)行加鎖保護(hù),一旦出現(xiàn)了指向同一個數(shù)據(jù)庫的多個SqliteDatabase對象同時在多個線程中被使用,那就跳脫了SqliteDatabase鎖保護(hù),就會導(dǎo)致數(shù)據(jù)庫出現(xiàn)被鎖的異常。因此在實踐中,需要保證同時訪問數(shù)據(jù)庫的SqliteDatabase對象僅有一個。(可以使用全局變量來保存數(shù)據(jù)庫對象,在整個數(shù)據(jù)源對象中使用同一個連接)
課外小知識:在Android SDK中提供了工具Sqlite3,在shell模式下,可以對數(shù)據(jù)庫進(jìn)行增刪改查。
cmd->adb shell ->sqlite3 <路徑>/<數(shù)據(jù)庫名> ->sqlite > select * from sqmple;
二、Android數(shù)據(jù)的云端服務(wù)
本質(zhì)上而言,云端存儲就是通過網(wǎng)絡(luò)將移動設(shè)備上的數(shù)據(jù)存儲到遠(yuǎn)端服務(wù)器上。在Android中,增加了一些輔助功能,使得整個流程的實現(xiàn)變得更為簡單。首先是通過Google賬號來標(biāo)識用戶身份。在android中,默認(rèn)支持使用Google賬號作為用戶身份的標(biāo)識,系統(tǒng)上各個應(yīng)用都可以通過賬號系統(tǒng)獲得用戶的登錄信息。其次,有了Google賬號,使得開發(fā)者不需要自行構(gòu)建后臺服務(wù)系統(tǒng)。
Android的云端數(shù)據(jù)存取由系統(tǒng)服務(wù)BackupManagerService來統(tǒng)一管理。當(dāng)應(yīng)用提交備份數(shù)據(jù)請求時,BackupManagerService會將該請求放入備份隊列中,該隊列會按照一定的控制邏輯定時提交到云端。當(dāng)有新應(yīng)用安裝到系統(tǒng)時,會觸發(fā)數(shù)據(jù)恢復(fù)事件,BackupManagerService會憑借應(yīng)用包名和用戶賬號從云端取出相應(yīng)的備份數(shù)據(jù),嘗試恢復(fù)。
在實踐中,Android會構(gòu)造一個派生自BackupAgent類的子類android.app.backup.BackupAgentHelper的對象,來更方便地構(gòu)建云端存儲組件。
Android不會自行將數(shù)據(jù)提交到云端,開發(fā)者需要顯性調(diào)用android.app.backup.BackupManager的dataChanged函數(shù)來觸發(fā)。
- import java.io.File;
- import java.io.IOException;
- import android.app.backup.BackupAgentHelper;
- import android.app.backup.BackupDataInput;
- import android.app.backup.BackupDataOutput;
- import android.app.backup.FileBackupHelper;
- import android.os.ParcelFileDescriptor;
- public class MyBackupAgent extends BackupAgentHelper {
- private static final String KEY = "my_backup";
- @Override
- public void onCreate() {
- //構(gòu)造文件讀寫對象,聲明需要備份的文件
- FileBackupHelper helper = new FileBackupHelper(this,"backup_file");
- addHelper(KEY,helper);
- super.onCreate();
- }
- @Override
- public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
- ParcelFileDescriptor newState) throws IOException {
- //調(diào)用父類方法,提交整個文件到云端
- super.onBackup(oldState, data, newState);
- }
- @Override
- public void onRestore(BackupDataInput data, int appVersionCode,
- ParcelFileDescriptor newState) throws IOException {
- // 調(diào)用父類方法,將從云端獲取的文件覆蓋本地文件
- super.onRestore(data, appVersionCode, newState);
- }
- @Override
- public void onRestoreFile(ParcelFileDescriptor data, long size,
- File destination, int type, long mode, long mtime)
- throws IOException {
- // TODO Auto-generated method stub
- super.onRestoreFile(data, size, destination, type, mode, mtime);
- }
和所有組件一樣,云端存儲組件是由系統(tǒng)進(jìn)行托管的。這就需要把組件的相關(guān)信息放入配置文件中。
<application android:backupAgent = "MyBackupAgent" ...>