1. 程式人生 > >輕量數據庫SQLiteDataBase的相關操作方法

輕量數據庫SQLiteDataBase的相關操作方法

isnull 返回 isa 般的 是否為空 keyword base pri 參考

一、查詢操作:

查詢操作比較復雜,主要有如下操作:

1 db.rawQuery(String sql, String[] selectionArgs);  
2 db.query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy);  
3 db.query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit);  
4 db.query(String distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit);

1、最為簡單,將所有的SQL語句組織到一個字符串中,selectionArgs就是占位符實際參數集

2、columns表示要查詢的列所有名稱集,selection表示WHERE之後的條件語句,可以使用占位符,groupBy指定分組的列名,having指定分組條件,配合groupBy使用,orderBy指定排序的列名

3、limit指定分頁參數

4、distinct可以指定“true”或“false”表示要不要過濾重復值。

selection、groupBy、having、orderBy、limit這幾個參數中不包括“WHERE”、“GROUP BY”、“HAVING”、“ORDER BY”、“LIMIT”等SQL關鍵字。
返回一個Cursor對象,代表數據集的遊標,有點類似於JavaSE中的ResultSet。

Cursor對象的常用方法:

 1 cursor.move(int offset); //以當前位置為參考,移動到指定行  
 2 cursor.moveToFirst();    //移動到第一行  
3 cursor.moveToLast(); //移動到最後一行 4 cursor.moveToPosition(int position); //移動到指定行 5 cursor.moveToPrevious(); //移動到前一行 6 cursor.moveToNext(); //移動到下一行 7 cursor.isFirst(); //是否指向第一條 8 cursor.isLast(); //是否指向最後一條 9 cursor.isBeforeFirst(); //是否指向第一條之前 10 cursor.isAfterLast(); //是否指向最後一條之後 11 cursor.isNull(int columnIndex); //指定列是否為空(列基數為0) 12 cursor.isClosed(); //遊標是否已關閉 13 cursor.getCount(); //總數據項數 14 cursor.getPosition(); //返回當前遊標所指向的行數 15 cursor.getColumnIndex(String columnName);//返回某列名對應的列索引值 16 cursor.getString(int columnIndex); //返回當前行指定列的值

二、添加、更新和刪除

1    db.executeSQL(String sql);  
2    db.executeSQL(String sql, Object[] bindArgs);//sql語句中使用占位符,然後第二個參數是實際的參數集  
3 
4 
5     db.insert(String table, String nullColumnHack, ContentValues values);  
6     db.update(String table, Contentvalues values, String whereClause, String whereArgs);  
7     db.delete(String table, String whereClause, String whereArgs);  

Insert:

table第一個參數表示操作表名;insert中的第二個參數表示如果插入的數據每一列都為空的話,需要指定此行中某一列的名稱,系統將此列設置為NULL,不至於出現錯誤;insert中的第三個參數是ContentValues類型的變量,是一組鍵值對組成,Columnkey代表列名,ColumnValue代表該列要插入的值;
Update:

update的第二個參數也很類似,只不過它是更新該字段key為最新的value值,第三個參數whereClause表示WHERE表達式,比如“age > ? and age < ?”等,whereArgs參數是占位符的實際參數值;

delete:

其參數基本一樣。

三、具體實例:

 1         //打開或創建test.db數據庫  
 2         SQLiteDatabase db = openOrCreateDatabase("test.db", Context.MODE_PRIVATE, null);  
 3         db.execSQL("DROP TABLE IF EXISTS person");  
 4         //創建person表  
 5         db.execSQL("CREATE TABLE person (_id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, age SMALLINT)");  
 6         Person person = new Person();  
 7         person.name = "john";  
 8         person.age = 30;  
 9         //插入數據  
10         db.execSQL("INSERT INTO person VALUES (NULL, ?, ?)", new Object[]{person.name, person.age});  
11           
12         person.name = "david";  
13         person.age = 33;  
14         //ContentValues以鍵值對的形式存放數據  
15         ContentValues cv = new ContentValues();  
16         cv.put("name", person.name);  
17         cv.put("age", person.age);  
18         //插入ContentValues中的數據  
19         db.insert("person", null, cv);  
20           
21         cv = new ContentValues();  
22         cv.put("age", 35);  
23         //更新數據  
24         db.update("person", cv, "name = ?", new String[]{"john"});  
25           
26         Cursor c = db.rawQuery("SELECT * FROM person WHERE age >= ?", new String[]{"33"});  
27         while (c.moveToNext()) {  
28             int _id = c.getInt(c.getColumnIndex("_id"));  
29             String name = c.getString(c.getColumnIndex("name"));  
30             int age = c.getInt(c.getColumnIndex("age"));  
31             Log.i("db", "_id=>" + _id + ", name=>" + name + ", age=>" + age);  
32         }  
33         c.close();  
34           
35         //刪除數據  
36         db.delete("person", "age < ?", new String[]{"35"});  
37           
38         //關閉當前數據庫  
39         db.close();  
40           
41         //刪除test.db數據庫  
42 //      deleteDatabase("test.db");  
43     }  

四、SQLiteOpenHelper

SQLiteOpenHelper是SQLiteDatabse的一個幫助類,用來管理數據的創建和版本更新。一般的用法是定義一個類繼承SQLiteOpenHelper,並實現兩個回調方法,OnCreate(SQLiteDatabase db)和onUpgrade(SQLiteDatabse, int oldVersion, int newVersion)來創建和更新數據庫。

一般可以如下獲取幫助類的實例: mOpenHelper = new DatabaseHelper(getContext());

他有如下三個類定義:

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

public SQLiteOpenHelper(Context context, String name, int version)

public SQLiteOpenHelper(Context context)

二個回調函數:

public void onCreate(SQLiteDatabase db)

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

//獲取SQLiteDatabase實例

SQLiteDatabase db = getWritableDatabase();

SQLiteDatabase db = getReadableDatabase();

五、事務處理

SQLiteDatabase的beginTransaction()方法可以開啟一個事務,程序執行到endTransaction() 方法時會檢查事務的標誌是否為成功,如果程序執行到endTransaction()之前調用了setTransactionSuccessful() 方法設置事務的標誌為成功則提交事務,如果沒有調用setTransactionSuccessful() 方法則回滾事務。

事務處理應用:很多時候我們需要批量的向Sqlite中插入大量數據時,單獨的使用添加方法導致應用響應緩慢, 因為sqlite插入數據的時候默認一條語句就是一個事務,有多少條數據就有多少次磁盤操作。為了保證數據的一致性,避免出現數據缺失等情況。

 1 SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
 2 //開啟事務
 3 db.beginTransaction();
 4 try{
 5             //批量處理操作
 6             //do something
 7            db.execSQL("SQL語句", new Object[]{});
 8            db.execSQL("SQL語句", new Object[]{});
 9             //設置事務標誌為成功,當結束事務時就會提交事務
10             db.setTransactionSuccessful();
11 }
12 catch(Exception e){
13 }
14 finally{
15            //結束事務
16           db.endTransaction();
17 }

註:以上代碼參考:

http://blog.csdn.net/li12412414/article/details/51958774

http://blog.csdn.net/xiaanming/article/details/8679521

輕量數據庫SQLiteDataBase的相關操作方法