qileilove

          blog已經(jīng)轉(zhuǎn)移至github,大家請(qǐng)?jiān)L問(wèn) http://qaseven.github.io/

          android SQLite數(shù)據(jù)庫(kù)存儲(chǔ)數(shù)據(jù)

          簡(jiǎn)介

            SQLite是輕量級(jí)嵌入式數(shù)據(jù)庫(kù)引擎,它支持 SQL 語(yǔ)言,并且只利用很少的內(nèi)存就有很好的性能。Android 集成了 SQLite 數(shù)據(jù)庫(kù) Android 在運(yùn)行時(shí)(run-time)集成了 SQLite,所以每個(gè) Android 應(yīng)用程序都可以使用 SQLite 數(shù)據(jù)庫(kù)。

            對(duì)于熟悉 SQL 的開(kāi)發(fā)人員來(lái)時(shí),在 Android 開(kāi)發(fā)中使用 SQLite 相當(dāng)簡(jiǎn)單。但是,由于 JDBC 會(huì)消耗太多的系統(tǒng)資源,所以 JDBC 對(duì)于手機(jī)這種內(nèi)存受限設(shè)備來(lái)說(shuō)并不合適。因此,Android 提供了一些新的 API 來(lái)使用 SQLite 數(shù)據(jù)庫(kù),Android 開(kāi)發(fā)中,程序員需要學(xué)使用這些 API。

            數(shù)據(jù)庫(kù)存儲(chǔ)在 data/< 項(xiàng)目文件夾 >/databases/ 下。 Android 開(kāi)發(fā)中使用 SQLite 數(shù)據(jù)庫(kù) Activites 可以通過(guò) Content Provider 或者 Service 訪問(wèn)一個(gè)數(shù)據(jù)庫(kù)。

            創(chuàng)建數(shù)據(jù)庫(kù)

            創(chuàng)建數(shù)據(jù)庫(kù)只要自定義一個(gè)類繼承SQLiteOpenHelper即可。在SQLiteOpenHelper 的子類,至少需要實(shí)現(xiàn)三個(gè)方法:

            1 構(gòu)造函數(shù),調(diào)用父類 SQLiteOpenHelper 的構(gòu)造函數(shù)。這個(gè)方法需要四個(gè)參數(shù):上下文環(huán)境(例如,一個(gè) Activity),數(shù)據(jù)庫(kù)名字,一個(gè)可選的游標(biāo)工廠(通常是 Null),一個(gè)代表你正在使用的數(shù)據(jù)庫(kù)模型版本的整數(shù)。

            2 onCreate()方法,它需要一個(gè) SQLiteDatabase 對(duì)象作為參數(shù),根據(jù)需要對(duì)這個(gè)對(duì)象填充表和初始化數(shù)據(jù)。

            3 onUpgrage() 方法,它需要三個(gè)參數(shù),一個(gè) SQLiteDatabase 對(duì)象,一個(gè)舊的版本號(hào)和一個(gè)新的版本號(hào),這樣你就可以清楚如何把一個(gè)數(shù)據(jù)庫(kù)從舊的模型轉(zhuǎn)變到新的模型。(Android中數(shù)據(jù)庫(kù)升級(jí)使用SQLiteOpenHelper類onUpgrade方法說(shuō)明)

            下面示例代碼展示了如何繼承 SQLiteOpenHelper 創(chuàng)建數(shù)據(jù)庫(kù):

          public class DBHelper extends SQLiteOpenHelper {
          // 數(shù)據(jù)庫(kù)名稱
          public static final String DBNAME = "crius.db";
          // 數(shù)據(jù)庫(kù)版本
          public static final int VERSION = 2;
          public DBHelper(Context c, String dbName) {
          super(c, DBNAME, null, VERSION);
          }
          @Override
          public void onCreate(SQLiteDatabase db) {
          // TODO 創(chuàng)建數(shù)據(jù)庫(kù)后,創(chuàng)建表
          db.execSQL("create table if not exists draftbox(pkid integer primary key autoincrement,formcode varchar(20),date datetime,summary varchar(100), context text, imagefolder varchar(50)) ");
          }
          @Override
          public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
          // TODO 更改數(shù)據(jù)庫(kù)版本的操作
          }
          @Override
          public void onOpen(SQLiteDatabase db) {
          super.onOpen(db);
          // TODO 每次成功打開(kāi)數(shù)據(jù)庫(kù)后首先被執(zhí)行
          }
          }

            對(duì)數(shù)據(jù)庫(kù)表進(jìn)行操作

            接下來(lái)討論具體如何插入數(shù)據(jù)、查詢數(shù)據(jù)、刪除數(shù)據(jù)等等。調(diào)用 getReadableDatabase() 或 getWriteableDatabase() 方法,你可以得到 SQLiteDatabase 實(shí)例,具體調(diào)用那個(gè)方法,取決于你是否需要改變數(shù)據(jù)庫(kù)的內(nèi)容。有兩種方法可以對(duì)數(shù)據(jù)庫(kù)表進(jìn)行操作:使用execSQL方法執(zhí)行SQL語(yǔ)句;使用insert、delete、update和query方法,把SQL語(yǔ)句的一部分作為參數(shù)。

            插入數(shù)據(jù):

            使用SQLiteDatabase.insert()方法來(lái)插入數(shù)據(jù):

          public voidinsert(int formCode, String summary, String context, String folder) {
          Log.i("SQLite", "----insert----");
          ContentValues values = new ContentValues();
          values.put("formcode", formCode);
          values.put("date", (new TaskDate()).toString());
          values.put("summary", summary);
          values.put("context", context);
          values.put("imagefolder", folder);
          SQLiteDatabase db = getWritableDatabase();
          db.beginTransaction();
          try {   db.insert("draftbox",null, values);db.setTransactionSuccessful();     } catch (Exception e) {
          return ;
          } finally {
          db.endTransaction();
          }
          db.close();}

            使用SQLiteDatabase.execSQL()方法來(lái)插入數(shù)據(jù):

          public int insert(Person person) {     Log.i("SQLite", "----insert----");      SQLiteDatabase db = getWritableDatabase();     db.beginTransaction();     try {          db.execSQL("insert into " + "draftbox"                  + " values(?, ?, ?, ?)", new Object[] { person.formCode,                  person.summary, person.context, person.folder});          db.setTransactionSuccessful();     } catch (Exception e) {          return 0;     } finally {          db.endTransaction();     }     db.close();     return 1; }  

            刪除數(shù)據(jù):

            使用SQLiteDatabase.delete()方法來(lái)刪除數(shù)據(jù)(刪除所有數(shù)據(jù)db.delete(<表名>, null, null)):

          public int delete(Person person) {
          Log.e("SQLite", "----delete----");
          SQLiteDatabase db = dbHelper.getWritableDatabase();
          db.beginTransaction();
          try {
          db.delete(Person.TABLENAME , "id"+ "=?", new String[] { person.id});
          db.setTransactionSuccessful();
          } catch (Exception e) {
          return 0;
          } finally {
          db.endTransaction();
          }
          db.close();
          return 1;
          }

            使用SQLiteDatabase.execSQL()方法來(lái)刪除數(shù)據(jù):

          public int delete(Person person) {
          Log.e("SQLite", "----delete----");
          SQLiteDatabase db = dbHelper.getWritableDatabase();
          db.beginTransaction();
          try {
          db.execSQL("delete from " + Person.TABLENAME + " where id = ?",
          new Object[] { person.id });
          db.setTransactionSuccessful();
          } catch (Exception e) {
          return 0;
          } finally {
          db.endTransaction();
          }
          db.close();
          return 1;
          }



           修改數(shù)據(jù):

            使用SQLiteDatabase.update()方法來(lái)修改數(shù)據(jù):

          public int update(Person person) { 
               Log.e("SQLite", "----update----"); 
               ContentValues values = new ContentValues();
               values.put("formcode", person.formCode);
               values.put("summary", person.summary);
               values.put("context", person.context);
               values.put("imagefolder", person.folder);
               SQLiteDatabase db = dbHelper.getWritableDatabase(); 
               db.beginTransaction(); 
               try { 
                   db.update(Person.TABLENAME, values , "id" + "=?",new String[] {person.id});
                   db.setTransactionSuccessful(); 
               } catch (Exception e) { 
                   return 0; 
               } finally { 
                   db.endTransaction(); 
               } 
               db.close(); 
               return 1; 

            使用SQLiteDatabase.execSQL()方法來(lái)修改數(shù)據(jù):

          public int update(Person person) { 
               Log.e("SQLite", "----update----"); 
               SQLiteDatabase db = dbHelper.getWritableDatabase(); 
               db.beginTransaction(); 
               try { 
                    db.execSQL("update " + Person.TABLENAME 
                             + " set formCode=?, summary=?, context=? where id=?", new Object[] { 
                             person.formCode,person.summary, person.context, person.id}); 
                    db.setTransactionSuccessful(); 
               } catch (Exception e) { 
                    return 0; 
               } finally { 
                    db.endTransaction(); 
               } 
               db.close(); 
               return 1; 

            查詢數(shù)據(jù):

            使用SQLiteDatabase.rawQuery()方法來(lái)查詢數(shù)據(jù):

            Cursor c=db.rawQuery( "SELECT formCode,summary,context,imagefolder FROM draftbox WHERE id=? ", person.id);

            使用SQLiteDatabase.query()方法來(lái)查詢數(shù)據(jù):

          /**

          * @param table 表名
          * @param columns 列名字符串?dāng)?shù)組
          * @param selection 篩選條件
          * @param selectionArgs 篩選條件參數(shù)數(shù)組
          * @param groupBy 分組字段
          * @param having 
          * @param orderBy 排序字段
          * @return Cursor對(duì)象
          */

          public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy); Cursor c=db.query("draftbox" , columns, selection, selectionArgs,groupBy, having, orderBy);




          不管你如何執(zhí)行查詢,都會(huì)返回一個(gè) Cursor,這是 Android 的 SQLite 數(shù)據(jù)庫(kù)游標(biāo),Cursor 是每行的集合。

            使用 moveToFirst() 定位第一行。

            你必須知道每一列的名稱。

            你必須知道每一列的數(shù)據(jù)類型。

            Cursor 是一個(gè)隨機(jī)的數(shù)據(jù)源。

            所有的數(shù)據(jù)都是通過(guò)下標(biāo)取得。

            關(guān)于 Cursor 的重要方法:

            close()
            關(guān)閉游標(biāo),釋放資源
            copyStringToBuffer(int columnIndex, CharArrayBuffer buffer)
            在緩沖區(qū)中檢索請(qǐng)求的列的文本,將將其存儲(chǔ)
            getColumnCount()
            返回所有列的總數(shù)
            getColumnIndex(String columnName)
            返回指定列的名稱,如果不存在返回-1
            getColumnIndexOrThrow(String columnName)
            從零開(kāi)始返回指定列名稱,如果不存在將拋出IllegalArgumentException 異常。
            getColumnName(int columnIndex)
            從給定的索引返回列名
            getColumnNames()
            返回一個(gè)字符串?dāng)?shù)組的列名
            getCount()
            返回Cursor 中的行數(shù)
            moveToFirst()
            移動(dòng)光標(biāo)到第一行
            moveToLast()
            移動(dòng)光標(biāo)到最后一行
            moveToNext()
            移動(dòng)光標(biāo)到下一行
            moveToPosition(int position)
            移動(dòng)光標(biāo)到一個(gè)絕對(duì)的位置
            moveToPrevious()
            移動(dòng)光標(biāo)到上一行

            現(xiàn)在讓我們看看如何循環(huán) Cursor 取出我們需要的數(shù)據(jù):

          Cursor result=db.rawQuery("SELECT pkid, date, context FROM draftbox",null);
          result.moveToFirst(); 
          while (!result.isAfterLast()) { 
               int id=result.getInt(0); 
               String date=result.getString(1); 
               //通過(guò)字段字取值
               String context=result.getString(result.getColumnIndex("context")); 
               result.moveToNext(); 
          }
          result.close(); 
           
            SQLite 數(shù)據(jù)庫(kù)管理工具

            在 Android 中使用 SQLite 數(shù)據(jù)庫(kù)管理工具 在其他數(shù)據(jù)庫(kù)上作開(kāi)發(fā),一般都使用工具來(lái)檢查和處理數(shù)據(jù)庫(kù)的內(nèi)容,而不是僅僅使用數(shù)據(jù)庫(kù)的 API。

            使用 Android 模擬器,有兩種可供選擇的方法來(lái)管理數(shù)據(jù)庫(kù)。

            首先,模擬器綁定了 sqlite3 控制臺(tái)程序,可以使用 adb shell 命令來(lái)調(diào)用他。只要你進(jìn)入了模擬器的 shell,在數(shù)據(jù)庫(kù)的路徑執(zhí)行 sqlite3 命令就可以了。

            數(shù)據(jù)庫(kù)文件一般存放在: /data/data/<項(xiàng)目文件夾>/databases/<數(shù)據(jù)庫(kù)名>如果你喜歡使用更友好的工具,你可以把數(shù)據(jù)庫(kù)拷貝到你的開(kāi)發(fā)機(jī)上,使用 SQLite-aware 客戶端來(lái)操作它。這樣的話,你在一個(gè)數(shù)據(jù)庫(kù)的拷貝上操作,如果你想要你的修改能反映到設(shè)備上,你需要把數(shù)據(jù)庫(kù)備份回去。

            把數(shù)據(jù)庫(kù)從設(shè)備上考出來(lái),你可以使用 adb pull 命令(或者在 IDE 上做相應(yīng)操作)。

            存儲(chǔ)一個(gè)修改過(guò)的數(shù)據(jù)庫(kù)到設(shè)備上,使用 adb push 命令。 一個(gè)最方便的 SQLite 客戶端是 FireFox SQLite Manager 擴(kuò)展,它可以跨所有平臺(tái)使用。

          posted on 2013-08-27 10:16 順其自然EVO 閱讀(2281) 評(píng)論(0)  編輯  收藏


          只有注冊(cè)用戶登錄后才能發(fā)表評(píng)論。


          網(wǎng)站導(dǎo)航:
           
          <2013年8月>
          28293031123
          45678910
          11121314151617
          18192021222324
          25262728293031
          1234567

          導(dǎo)航

          統(tǒng)計(jì)

          常用鏈接

          留言簿(55)

          隨筆分類

          隨筆檔案

          文章分類

          文章檔案

          搜索

          最新評(píng)論

          閱讀排行榜

          評(píng)論排行榜

          主站蜘蛛池模板: 惠安县| 桦川县| 延安市| 新民市| 瑞昌市| 淮南市| 曲周县| 常德市| 房山区| 禹城市| 宜州市| 申扎县| 柏乡县| 娱乐| 英超| 合阳县| 巫溪县| 和硕县| 广西| 万年县| 丹东市| 沈阳市| 崇信县| 英山县| 漠河县| 麟游县| 栾川县| 双江| 绵竹市| 广灵县| 乐安县| 黄大仙区| 琼结县| 蛟河市| 修文县| 云林县| 马鞍山市| 株洲市| 罗田县| 盐边县| 腾冲县|