使用Sqlite資料庫儲存資料

來源:互聯網
上載者:User

標籤:ase   架構   dex   and   函數   命令   sel   move   update   

1.Sql基本命令

1.1.建立表

  表是有行和列組成的,列稱為欄位,行稱為記錄。

  使用CREATE命令來建立表:

  

1   CREATE TABLE tab_student (studentId INTEGER PRIMARY KEY AUTOINCREMENT, 2                             studentName VARCHAR(20), 3                             studentAge INTEGER);

 

 

1.2.插入記錄(行)

  使用INSERT命令可以一次插入一條記錄,INSERT命令的一般格式為:

  

INSERT INTO tab_student (studentId, studentName, studentAge) VALUES (1, “jack”, 23);

 

1.3.更新記錄(行)

  使用UPDATE命令可以更新表中的記錄,該命令可以修改一個表中一行或者多行中的一個或多個欄位。UPDATE命令的一般格式為:

  

UPDATE tab_student SET studentName=”tom”, studentAge=”25” WHERE studentId=1;

 

 

1.4.刪除記錄(行)

  使用DELETE命令可以刪除表中的記錄,DELETE命令的一般格式為:

DELETE FROM tab_student WHERE studentId=1;

 

1.5.查詢記錄(行)

  SELECT命令是查詢資料庫的唯一命令。SELECT命令也是SQL命令中最大、最複雜的命令。

 

  SELECT命令的通用形式如下:

  SELECT [distinct] heading 

  FROM tables 

  WHERE predicate 

  GROUP BY columns 

  HAVING predicate 

  ORDER BY columns 

  LIMIT count,offset;

  其中,每個關鍵字(如FROM、WHERE、HAVING等)都是一個單獨的子句,每個子句由關鍵字和跟隨的參數構成。GROUP BY和HAVING一起工作可以對GROUP BY進行約束。ORDER BY使記錄集在返回之前按一個或多個欄位的值進行排序,可以指定排序方式為ASC(預設的升序)或DESC(降序)。此外,還可以使用LIMIT限定結果集的大小和範圍,count指定返回記錄的最大數量,offset指定位移的記錄數。

  在上述的SELECT命令通用形式中,除了SELECT之外,所有的子句都是可選的。目前最常用的SELECT命令由三個子句組成:SELECT、FROM、WHERE,其基本文法形式如下:

  SELECT heading FROM tables WHERE predicate;

  比如,要查詢剛才插入的記錄,便可以使用如下的陳述式完成:

  

SELECT studentId, studentName, studentAge FROM tab_student WHERE studentId=1;

 

2.資料庫操作輔助類SQLiteOpenHelper

 

Android提供了一個重要的類SQLiteOpenHelper,用於輔助使用者對SQLite資料庫進行操作。

 

  SQLiteOpenHelper的建構函式原型如下:

 

  public SQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version);

 

  其中,參數context表示應用程式啟動並執行環境,包含應用程式所需的共用資源。參數name表示Android的資料庫名字。參數factory是SQLiteDatabase.CursorFactory類對象,用於儲存查詢Android SQLite資料庫的結果集。參數version表示應用程式所用的資料庫的版本,該版本並非SQLite的真正版本,而是指定應用程式中的SQLite資料庫的版本,當該版本號碼發生變化時,將會觸發SQLiteOpenHelper類中的onUpgrade()或onDowngrade()方法。

SQLiteOpenHelper類的所有方法1所示。

 

  

 

 其中,close()方法用於關閉SQLiteOpenHelper對象中的SQLite資料庫;getReadableDatabase()方法和getWriteableDatabase()方法類似,getReadableDatabase()方法以唯讀狀態開啟SQLiteOpenHelper對象中指定的SQLite資料庫,任何想要修改資料庫的操作都是不允許的;getWriteableDatabase()方法也是開啟資料庫,但是允許資料庫正常的讀/寫操作;在一個不存在的資料庫上調用任何方法時,都會隱式的調用SQLiteOpenHelper對象的onCreate()方法;當應用程式第一次訪問資料庫時,則會調用onOpen()方法,但是,如果版本號碼發生了變化的話,則會調用onUpgrade()或onDowngrade()方法。

 

3.資料庫類SQLiteDatabase

SQLiteDatabase類用來完成對資料庫的操作任務,比如表的選擇、插入、更新和刪除語句等。

 

  SQLiteDatabase類中常用的用於執行SQL語句的方法有以下一些。

 

  (1)execSQL()方法:

 

  public void execSQL (String sql);

 

  public void execSQL (String sql, Object[] bindArgs);

 

  (2)query()方法:

 

  public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String  groupBy, String  having,String orderBy, String limit);

 

  public Cursor query (boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit, CancellationSignal cancellationSignal);

 

  public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String  having,String orderBy);

 

  public Cursor query (boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit);

 

 

  (3)queryWithFactory()方法:

          public Cursor queryWithFactory (SQLiteDatabase.CursorFactory cursorFactory, boolean distinct, String table, String[]columns, String selection, String[] selectionArgs, String groupBy,  String having, String  orderBy, String  limit,CancellationSignal cancellationSignal);

  public Cursor queryWithFactory (SQLiteDatabase.CursorFactory cursorFactory, boolean distinct, String table, String[]columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit);

  (4)rawQuery()方法:

  public Cursor rawQuery (String sql, String[] selectionArgs, CancellationSignal cancellationSignal);

  public Cursor rawQuery (String sql, String[] selectionArgs);

  (5)rawQueryWithFactory()方法:

  public Cursor rawQueryWithFactory (SQLiteDatabase.CursorFactory cursorFactory, String sql, String[]  selectionArgs,String editTable);

  public Cursor rawQueryWithFactory (SQLiteDatabase.CursorFactory cursorFactory, String sql, String[]  selectionArgs,String editTable, CancellationSignal cancellationSignal);

  其中,execSQL()方法都有一個參數sql,這個參數是一個SQL語句。第二個參數bindArgs接收一個數組,數組中的每個成員捆綁了一個查詢。execSQL()方法用於運行那些沒有傳回值的查詢語句,比如建立、插入、更新和修改表。

  query()方法和queryWithFactory()方法是在資料庫中運行一些輕量級的單查詢語句,參數包括table、columns、groupBy、having、orderBy、limit等SQL語句關鍵字。這些方法允許將SQL語句傳遞給相關方法,而不必直接使用SQL語句。

  rawQuery()方法和rawQueryWithFactory()方法也都有一個參數sql,用於執行SQL查詢語句,傳回值是Cursor對象。這兩個方法都有一個版本能夠接收一個字串數組selectionArgs作為參數,通過這個參數,SQLiteDatabase對象將把捆綁的SQL語句中的問號(?)用這個數組中的值代替,並按照一一對應的位置關係進行取代。

  SQLiteDatabase類提供了大約50個方法,除此之外還有一些用於開啟資料庫的方法(如openDatabase()、openOrCreateDatabase()等),用於管理SQLite事務的方法(如beginTransaction()、endTransaction()等),用於測試資料庫是否被鎖住的方法(如isDbLockedByCurrentThread()、isDbLockedByOtherThread()等),以及擷取資料庫基本資料的方法(如getMaximumSiza()、getVersion()等)。這裡就不一一介紹了,具體可以參閱SQLiteDatabase類的API協助文檔。

4.遊標類Cursor

在Android中,查詢資料是通過Cursor類來實現的,當我們使用SQLiteDatabase.query()或SQLiteDatabase.rawQuery()方法時,會得到一個Cursor對象,Cursor指向的就是每一條記錄,它提供了很多有關查詢的方法,2所示。

 5.封裝介面

有了以上的基礎,我們便可以按照MVC的架構,封裝一個介面層,在該介面層中實現對SQLite資料庫的具體操作。

  以下分別以添加資料、更新資料、查詢資料為例講解其具體的實現方法。在實現這些方法之前,我們首先需要建立一張表。這裡我建立了一個名為MySQLiteOpenHelper的類,讓它繼承自SQLiteOpenHelper類,並實現了SQLiteOpenHelper類的onCreate()方法,在該方法裡實現建立一張表的操作,具體原始碼如下:

1     /*2      * Function  :    建立表3      * Author    :    部落格園-依舊淡然4      */5     public void onCreate(SQLiteDatabase db) {6         db.execSQL("CREATE TABLE tab_student (studentId INTEGER PRIMARY KEY AUTOINCREMENT, " +                                                "studentName VARCHER(20), " +                                                              "studentAge INTEGER)");7     }

通過以上的代碼,我們建立了一張名為“tab_student”的表,並在該表中建立了三個欄位,分別為:studentId、studentName和studentAge。並且指定了studentId欄位作為該表的主鍵。

 

5.1添加資料

添加資料可以使用SQLiteDatabase.execSQL(String sql, Object[] bindArgs)方法來實現,具體如下:

1     /*2      * Function  :    添加資料3      * Author    :    部落格園-pres_cheng4      */5     public void addStudentInfo(Student student) {6         db = mySQLiteOpenHelper.getWritableDatabase();7         db.execSQL("INSERT INTO tab_student (studentId, studentName, studentAge) values (?, ?, ?)", 8           new Object[] {student.getStudentId(), student.getStudentName(), student.getStudentAge()});9     }

其中,通過第二個參數bindArgs,使SQL語句中的問號(?)與這個數組中的值形成一一對應關係,從而將值寫入到“tab_student”表中的對應欄位中。

 

5.2更新資料

  更新資料的方法與添加資料的方法大致相同,具體如下:

 

1    /*2     * Function  :    更新資料3     * Author    :    部落格園-pres_cheng4     */5    public void updateStudentInfo(Student student) {6        db = mySQLiteOpenHelper.getWritableDatabase();7        db.execSQL("UPDATE tab_student SET studentName = ?, studentAge = ? WHERE studentId = ?",           new Object[] {student.getStudentName(), student.getStudentAge(), student.getStudentId()});8    }

5.3查詢資料

   查詢資料時,因為需要返回查詢的結果,所以需要使用SQLiteDatabase.rawQuery()方法將查詢的結果返回,具體如下:

1     /* 2      * Function  :    查詢資料 3      * Author    :    部落格園-pres_cheng 4      */ 5     public Student findStudentInfo(int id) { 6         db = mySQLiteOpenHelper.getWritableDatabase(); 7         String sql = "SELECT studentId, studentName, studentAge FROM tab_student WHERE studentId = ?"; 8         Cursor cursor = db.rawQuery(sql, new String[] {String.valueOf(id)}); 9         if(cursor.moveToNext()) {10             return new Student(cursor.getInt(cursor.getColumnIndex("studentId")),                                       cursor.getString(cursor.getColumnIndex("studentName")),11                                cursor.getInt(cursor.getColumnIndex("studentAge")));12         }13         return null;14     }

可以看出,通過使用SQLiteDatabase.rawQuery()方法可以將查詢到的結果存入Cursor對象中。然後,我們可以使用Cursor對象的getXXX()方法將查詢結果從Cursor對象中取出來。

  當然了,我們還可以根據實際的需要,去實現更多的介面方法,比如,刪除資料、擷取資料列表、擷取資料個數等等。

  封裝好了以上的這些介面方法,便可以很方便的在程式中直接調用這些方法,不必再去關心底層資料庫的調用,而將精力放在UI介面的設計實現上。

使用Sqlite資料庫儲存資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.