android下SQLite學習筆記

參考博客http://blog.csdn.net/conowen/article/details/7276417

1、SQLite簡單介紹

SQ爲Structured Query (結構化查詢)的縮寫,Lite表示輕量級。SQLite是一款開源的關係型數據庫。幾乎可以支持所有現代編程語言和各種操作系統,SQLite的最新版本爲SQLite 3。


SQLite的特性: 
1. ACID事務 
2. 零配置 – 無需安裝和管理配置 
3. 儲存在單一磁盤文件中的一個完整的數據庫 
4. 數據庫文件可以在不同字節順序的機器間自由的共享 
5. 支持數據庫大小至2TB 
6. 足夠小, 大致3萬行C代碼, 250K , 運行時佔用內存大概幾百K。
7. 比一些流行的數據庫在大部分普通數據庫操作要快 
8. 簡單, 輕鬆的API 
9. 包含TCL綁定, 同時通過Wrapper支持其他語言的綁定 
10. 良好註釋的源代碼, 並且有着90%以上的測試覆蓋率 
11. 獨立: 沒有額外依賴 
12. Source完全的Open, 你可以用於任何用途, 包括出售它 
13. 支持多種開發語言,C, PHP, Perl, Java, ASP.NET,Python 



2、SQLite數據庫相關操作方法

對SQLite數據庫的操作一般包括:創建一個數據庫,打開數據庫,關閉數據庫,刪除數據庫。


2.1、創建和打開數據庫的方法:

public SQLiteDatabase openOrCreateDatabase (String name, int mode, SQLiteDatabase.CursorFactory factory)

使用openOrCreateDatabase()方法來創建,若數據庫不存在,則會創建新數據庫,若存在,則打開數據庫。

第一個參數————爲數據庫的名字,string類型。

第二個參數————爲常量,如下所示

常量                                                                             含義
MODE_PRIVATE                          默認模式,值爲0,文件只可以被調用該方法的應用程序訪問

MODE_WORLD_READABLE            所有的應用程序都具有對該文件讀的權限。

MODE_WORLD_WRITEABLE            所有的應用程序都具有對該文件寫的權限。

第三個參數————當query方法被調用時,用來實例化cursor,通常爲null

返回值爲一個SQLiteDatabase對象


2.2、關閉SQLite數據庫  db.close()

對數據庫操作完畢之後,就要關閉數據庫,否則會拋出SQLiteException異常。關閉數據庫只需調用成SQLiteDatabase對象的.close()方法即可。


2.3、刪除數據庫 

直接調用deleteDatebase()方法即可,如:

[java] view plaincopy
  1. this.deleteDatabase("mysqlite.db")  



3、SQLite數據庫中(Table )“表”的操作方法


        首先要明確一點的是,一個數據庫可以有很多表,一個表中包含很多條數據,也就是說,在數據庫裏面保存數據其實是保存在Table (表)裏面的。對已經存在和已經創建的數據庫操作一般包括:創建表,往表添加數據,從表中刪除數據,修改表中的數據,查詢表中的數據,刪除已存在的表。


3.1創建一個表   public void execSQL(String sql)


通過調用數據庫的execSQL (String sql)方法可以創建一個table(表),關於execSQL(String sql)方法的詳細可以參看以下的官方說明。

params

sql 一般的sql語句

throws

SQLException 如果SQL語句有錯誤

事實上,execSQL (String sql)方法的參數“sql“是SQL語句,爲字符串類型。如

[java] view plaincopy
  1. SQLiteDatabase db;  
  2.  String sql = "CREATE  TABLE pic (_id INTEGER PRIMARY KEY , filename VARCHAR, data TEXT)";  
  3. db.execSQL(sql);  
其中,android默認_id INTEGER PRIMARY KEY,必須加上,否則報錯,可以寫爲CREATE  TABLE pic (_id INTEGER PRIMARY KEY AUTOINCREMENT , filename VARCHAR, data TEXT)這樣可以自動遞增表號,讀取數據時作爲行號.不讀即可.

關於SQL語句可參看相關SQL的編程資料。

另外通過execSQL()方法,還可以實現向表中“插入”數據,“刪除”數據。

同樣是通過不同的SQL語句實現的。

[java] view plaincopy
  1. db.execSQL(sql);//sql爲標準的SQL語句  


另外:讀取表中數據也可以用rawQuery();方法來讀取。

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

Since: API Level 1

Runs the provided SQL and returns a Cursor over the result set.

Parameters
sql the SQL query. The SQL string must not be ; terminated
selectionArgs You may include ?s in where clause in the query, which will be replaced by the values from selectionArgs. The values will be bound as Strings.
Returns
  • Cursor object, which is positioned before the first entry. Note thatCursors are not synchronized, see the documentation for more details.

        雖然db.execSQL(sql);方法也可以實現insert和delete操作,另外db.rawQuery(sql, selectionArgs);也可以查詢表中的某一條數據,但是由於涉及到標準SQL語句,所以一般來說,除了新建table是用execSQL(sql)方法和3.6點的刪除一個table,其他的如insert,delete,query操作還是建議使用以下方法。


3.2、向表中插入一條數據

          往數據庫的table插入數據,可以直接調用db.insert()方法插入,但是insert()方法中的第三個參數是一個ContentValues的,其實也就是一個map,包含了一些鍵值對(key-value)。通過contentValues的put方法,可以把鍵值對放進contentValues裏面,然後再通過db.insert()方法插到數據庫的table中。

public long insert(String table,String nullColumnHack, ContentValues values)

Since: API Level 1

Convenience method for inserting a row into the database.

insert的第一個參數是table的名字,第二個參數一般爲null,第三個參數是contentValues,表的一行的數據的鍵值對

若成功insert,就返回新插入row的id,不成功返回-1。

[java] view plaincopy
  1. ContentValues cv =new contentValues();  
  2. cv.put(num,1);  
  3. cv.put(data," 測試我的數據庫");  
  4. db.insert(table,null,cv);  

  1. ContentValues cv = new ContentValues(); 
  2. cv.put("name", et_name.getText().toString());  
  3. cv.put("phone", et_phone.getText().toString());  
  4.                 // name和phone爲列名  
  5. long res = sqldb.insert("addressbook"null, cv);// 插入數據  
  6.  if (res == -1) {  
  7.        Toast.makeText(SqliteActivity.this"添加失敗",  
  8.        Toast.LENGTH_SHORT).show();  
  9.   } else {  
  10.         Toast.makeText(SqliteActivity.this"添加成功",  
  11.         Toast.LENGTH_SHORT).show();  
  12.   }  


3.3、刪除table中的一條數據

直接調用數據庫的db.delete()方法。 

public intdelete(String table,String whereClause,String[] whereArgs)

Since: API Level 1

Convenience method for deleting rows in the database.

Parameters
table the table to delete from
whereClause the optional WHERE clause to apply when deleting. Passing null will delete all rows.
Returns
  • the number of rows affected if a whereClause is passed in, 0 otherwise. To remove all rows and get a count pass "1" as the whereClause.
第一個參數————table名
第二個參數————刪除的條件,爲字符串。如果爲null,則所有行都將刪除。
第三個參數————字符串數組,和whereClause配合使用。
                                 用法一、如果whereClause的條件已經直接給出,如“name= “ + num,num是傳入的參數。則whereArgs可設爲null。
                                 用法二、當在whereClause中包含”?”時,則whereArgs這個數組中的值將依次替換whereClause中出現的”?”

  1. int res = sqldb.delete("addressbook""name='大鐘'"null);  
  2.                 // 刪除列名name,行名爲“大鐘”的,這一行的所有數據,null表示這一行的所有數據  
  3.                 // 若第二個參數爲null,則刪除表中所有列對應的所有行的數據,也就是把table清空了。  
  4.                 // name='大鐘',大鐘要單引號的  
  5.                 // 返回值爲刪除的行數  
  6.                 if (res == 0) {  
  7.                     Toast.makeText(SqliteActivity.this"刪除失敗",  
  8.                             Toast.LENGTH_SHORT).show();  
  9.                 } else {  
  10.                     Toast.makeText(SqliteActivity.this"成刪除了" + res + "行的數據",  
  11.                             Toast.LENGTH_SHORT).show();  
  12.                 }  

3.4、修改表中數據

調用db.update()方法

public int update(String table,ContentValues values,String whereClause,String[] whereArgs)

Since: API Level 1

Convenience method for updating rows in the database.

Parameters
table the table to update in
values a map from column names to new column values. null is a valid value that will be translated to NULL.
whereClause the optional WHERE clause to apply when updating. Passing null will update all rows.
Returns
  • the number of rows affected

update()的是個參數請參看上面幾個方法的說明。

  1. cv.put("name""大鐘");  
  2.                 cv.put("phone""1361234567");  
  3.                 int res = sqldb.update("addressbook", cv, "name='張三'"null);  
  4.                 // 把name=張三所在行的數據,全部更新爲ContentValues所對應的數據  
  5.                 // 返回時爲成功更新的行數  
  6.                 Toast.makeText(SqliteActivity.this"成功更新了" + res + "行的數據",  
  7.                         Toast.LENGTH_SHORT).show();  


3.5、查詢表中的數據

調用db.query()方法。

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

Since: API Level 1

Query the given table, returning a Cursor over the result set.

Parameters
table The table name to compile the query against.
columns A list of which columns to return. Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used.
selection A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given table.
selectionArgs You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values will be bound as Strings.
groupBy A filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself). Passing null will cause the rows to not be grouped.
having A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself). Passing null will cause all row groups to be included, and is required when row grouping is not being used.
orderBy How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.
limit Limits the number of rows returned by the query, formatted as LIMIT clause. Passing null denotes no LIMIT clause.
Returns
  • Cursor object, which is positioned before the first entry. Note thatCursors are not synchronized, see the documentation for more details.
參數說明:

table————要查詢數據的表名

 

columns————要返回列的列名數組

 

selection————可選的where子句 ,如果爲null,將會返回所有的行

                                                                                                                      

selectionArgs————當在selection中包含”?”時,如果selectionArgs的值不爲null,則這個數組中的值將依次替換selection中出現的”?”

 

groupBy————可選的group by子句,如果其值爲null,將不會對行進行分組

 

having————可選的having子句,如果其值爲null,將會包含所有的分組

 

orderBy————可選的order by子句,如果其值爲null,將會使用默認的排序規則

 

limit————可選的limit子句,如果其值爲null,將不會包含limit子句


[java] view plaincopy
  1. Cursor cr=db.query("pic"nullnullnullnull,nullnull);//查詢數據庫的所有數據  

db.query(TABLE_NAME,new String[]{"_id","task_no","cons_no"},"task_no=? or task_no=?",

new String[]{"1234","2345"},null,null,null);

查詢表中,查找task_no=1234 task_no=2345對應列名爲"_id","task_no","cons_no"的數據

"1234","2345"代替"task_no=? or task_no=?"所在的問號

相當 select _id,task_no,cons_no from TABLE_NAME where task_no="1234" or task_no="2345";


返回值類型爲Cursor(遊標),Cursor的操作示意圖



然後通過調用Cursor的相關方法來操作查詢到的數據,關於Cursor的使用方法可以參看官方的說明文檔,下面列出一些常用的方法:


3.6、刪除一個table

通過db.execSQL(sql)方法實現,參數sql是SQL標準語句

db.execSQl("DROP TABLE mytable");


  

利用SQLiteOpenHelper來管理SQLite數據庫

SQLiteOpenHelper可以創建數據庫,和管理數據庫的版本。

在繼承SQLiteOpenHelper的類(extends SQLiteOpenHelper)裏面,通過複寫onCreate(SQLiteDatabase),onUpgrade(SQLiteDatabase, int, int) 和onOpen(SQLiteDatabase)(可選)來操作數據庫。


4.1、SQLiteOpenHelper()的具體用法

創建一個新的class如下所示,onCreate(SQLiteDatabase db)和onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)方法會被自動添加。

  1.   
  2. package com.conowen.sqlite;  
  3.   
  4. import android.content.Context;  
  5. import android.database.sqlite.SQLiteDatabase;  
  6. import android.database.sqlite.SQLiteDatabase.CursorFactory;  
  7. import android.database.sqlite.SQLiteOpenHelper;  
  8.   
  9. public class DBHelper extends SQLiteOpenHelper{  
  10.   
  11.     public DbHelper(Context context, String name, CursorFactory 
  12. factory,int version) {  
  13.         super(context, name, factory, version);  
  14.         // TODO Auto-generated constructor stub  
  15.     }  
  16.   
  17.     @Override  
  18.     public void onCreate(SQLiteDatabase db) {  
  19.         // TODO Auto-generated method stub  
  20.        String sql = "CREATE TABLE table_name(_id INTEGER PRIMARY KEY,"+
  21.        "filename VARCHAR, data TEXT)";
  22.        db.execSQL(sql);//創建成功後會在機子的data/data/<package name>/databases文件中
  23.           
  24.     }  
  25.   
  26.     @Override  
  27.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  28.         // TODO Auto-generated method stub  
  29.           
  30.     }  
  31.   
  32. }  
方法介紹:1 
  1.  public DbHelper(Context context, String name, CursorFactory 
  2. factory,int version) {  
  3.         super(context, name, factory, version);  
  4.         // TODO Auto-generated constructor stub  
  5.     }  

以上是SQLiteOpenHelper 的構造函數,當數據庫不存在時,就會創建數據庫,然後打開數據庫(過程已經被封裝起來了),再調用onCreate (SQLiteDatabase db)方法來執行創建表之類的操作。當數據庫存在時,SQLiteOpenHelper 就不會調用onCreate (SQLiteDatabase db)方法了,它會檢測版本號,若傳入的版本號高於當前的,就會執行onUpgrade()方法來更新數據庫和版本號。


2  oncreate 方法

public abstract void onCreate (SQLiteDatabase db)

Since: API Level 1

Called when the database is created for the first time. This is where the creation of tables and the initial population of the tables should happen.


3onUpgrade方法

public abstract void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) 

        更新數據庫,包括刪除表,添加表等各種操作。若版本是第一版,也就是剛剛建立數據庫,onUpgrade()方法裏面就不用寫東西,因爲第一版數據庫何來更新之說,以後發佈的版本,數據庫更新的話,可以在onUpgrade()方法添加各種更新的操作。

4、注意事項

創建完SQLiteOpenHelper 類之後,在主activity裏面就可以通過SQLiteOpenHelper.getWritableDatabase()或者getReadableDatabase()方法來獲取在SQLiteOpenHelper 類裏面創建的數據庫實例。(也就是說只有調用這兩種方法才真正地實例化數據庫)

getWritableDatabase() 方法————以讀寫方式打開數據庫,如果數據庫所在磁盤空間滿了,而使用的又是getWritableDatabase() 方法就會出錯。

                                                                         因爲此時數據庫就只能讀而不能寫,

getReadableDatabase()方法————則是先以讀寫方式打開數據庫,如果數據庫的磁盤空間滿了,就會打開失敗,但是當打開失敗後會繼續嘗試以只讀

                                                                          方式打開數據庫。而不會報錯





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章