標籤:傳回值 [] util string類 不能 table super 指標 判斷
在項目開發中,我們或多或少都會用到資料庫。在Android中,我們一般使用SQLite,因為Android在android.database.sqlite包封裝了很多SQLite操作的API。我自己寫了一個Demo來總結SQLite的使用,託管在Github上,大家可以點擊下載APK,也可以點擊下載源碼。Demo如下:
在使用SQLite時,我建議先下載一個本地SQLite用戶端來驗證操作,在本地寫的SQL語句運行正確後,再轉移到Android中。我用的是SQLite Expert Personal。
首先建立一個繼承在SQLiteOpenHelper的類,並重寫onCreate()和onUpgrade()方法。
public class OrderDBHelper extends SQLiteOpenHelper{ private static final int DB_VERSION = 1; private static final String DB_NAME = "myTest.db"; public static final String TABLE_NAME = "Orders"; public OrderDBHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { // create table Orders(Id integer primary key, CustomName text, OrderPrice integer, Country text); String sql = "create table if not exists " + TABLE_NAME + " (Id integer primary key, CustomName text, OrderPrice integer, Country text)"; sqLiteDatabase.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) { String sql = "DROP TABLE IF EXISTS " + TABLE_NAME; sqLiteDatabase.execSQL(sql); onCreate(sqLiteDatabase); }}
這個類主要用於建資料庫和建表用,我們再建立一個OrderDao用於處理所有的資料操作方法。在OrderDao鐘執行個體化OrderDBHelper:
public OrderDao(Context context) { this.context = context; ordersDBHelper = new OrderDBHelper(context);}
資料庫操作無外乎:“增刪查改”。對於“增刪改”這類對錶內容變換的操作,我們需先調用getWritableDatabase(),在執行的時候可以調用通用的execSQL(String sql)方法或對應的操作API:insert()、delete()、update()。而對“查”,需要調用getReadableDatabase(),這時就不能使用execSQL方法了,得使用query()或rawQuery()方法。下面開始一一介紹。
增加資料
在我的Demo中,有兩種增加資料操作:
初始化資料
在進入Demo程式時,先判斷表中是否有資料,如果表中沒有資料,我將先添加一些資料。在初始化資料時,因為一次性要添加的資料比較多,所以我直接採用的是execSQL方法:
db = ordersDBHelper.getWritableDatabase();db.beginTransaction();db.execSQL("insert into " + OrderDBHelper.TABLE_NAME + " (Id, CustomName, OrderPrice, Country) values (1, ‘Arc‘, 100, ‘China‘)");db.execSQL("insert into " + OrderDBHelper.TABLE_NAME + " (Id, CustomName, OrderPrice, Country) values (2, ‘Bor‘, 200, ‘USA‘)");db.execSQL("insert into " + OrderDBHelper.TABLE_NAME + " (Id, CustomName, OrderPrice, Country) values (3, ‘Cut‘, 500, ‘Japan‘)");db.execSQL("insert into " + OrderDBHelper.TABLE_NAME + " (Id, CustomName, OrderPrice, Country) values (4, ‘Bor‘, 300, ‘USA‘)");db.execSQL("insert into " + OrderDBHelper.TABLE_NAME + " (Id, CustomName, OrderPrice, Country) values (5, ‘Arc‘, 600, ‘China‘)");db.execSQL("insert into " + OrderDBHelper.TABLE_NAME + " (Id, CustomName, OrderPrice, Country) values (6, ‘Doom‘, 200, ‘China‘)");db.setTransactionSuccessful();
插入一條新資料
我們還可以使用insert(String table,String nullColumnHack,ContentValues values)方法來插入,ContentValues內部實現就是HashMap,但是兩者還是有差別的,ContenValues Key只能是String類型,Value只能儲存基本類型的資料,像string,int之類的,不能儲存物件這種東西:
public ContentValues() { // Choosing a default size of 8 based on analysis of typical // consumption by applications. mValues = new HashMap<String, Object>(8);}
使用insert()方法我們插入一條新資料(7, "Jne", 700, "China"),對於修改資料的操作我們一般當作事務(Transaction)處理:
db = ordersDBHelper.getWritableDatabase();db.beginTransaction();// insert into Orders(Id, CustomName, OrderPrice, Country) values (7, "Jne", 700, "China");ContentValues contentValues = new ContentValues();contentValues.put("Id", 7);contentValues.put("CustomName", "Jne");contentValues.put("OrderPrice", 700);contentValues.put("Country", "China");db.insertOrThrow(OrderDBHelper.TABLE_NAME, null, contentValues);db.setTransactionSuccessful();
刪除資料
刪除資料的方法除了execSQL還有delete(String table,String whereClause,String[] whereArgs),whereClause是刪除條件,whereArgs是刪除條件值數組。
db = ordersDBHelper.getWritableDatabase();db.beginTransaction();// delete from Orders where Id = 7db.delete(OrderDBHelper.TABLE_NAME, "Id = ?", new String[]{String.valueOf(7)});db.setTransactionSuccessful();
再看刪除的源碼,裡面會拼裝刪除條件和刪除條件值數組:
public int delete(String table, String whereClause, String[] whereArgs) { acquireReference(); try { SQLiteStatement statement = new SQLiteStatement(this, "DELETE FROM " + table + (!TextUtils.isEmpty(whereClause) ? " WHERE " + whereClause : ""), whereArgs); try { return statement.executeUpdateDelete(); } finally { statement.close(); } } finally { releaseReference(); }}
修改資料
修改資料和插入資料很相似,調用的方法除了execSQL還可以是update(String table,ContentValues values,String whereClause, String[] whereArgs):
db = ordersDBHelper.getWritableDatabase();db.beginTransaction();// update Orders set OrderPrice = 800 where Id = 6ContentValues cv = new ContentValues();cv.put("OrderPrice", 800);db.update(OrderDBHelper.TABLE_NAME, cv, "Id = ?", new String[]{String.valueOf(6)});db.setTransactionSuccessful();
尋找資料
尋找資料有兩個方法,一是public Cursor query(String table,String[] columns,String selection,String[] selectionArgs,String groupBy,String having,String orderBy,String limit);,另外一個是public Cursor rawQuery(String sql, String[] selectionArgs)。rawQuery的寫法類似上面的execSQL,在此不做介紹,query方法中的參數如下:
- table:表名稱
- columns:列名稱數組
- selection:條件字句,相當於where
- selectionArgs:條件字句,參數數組
- groupBy:分組列
- having:分組條件
- orderBy:排序列
- limit:分頁查詢限制
- Cursor:傳回值,相當於結果集ResultSet
我們可以看到返回的類型都是Cursor,Cursor是一個遊標介面,提供了遍曆查詢結果的方法,如移動指標方法move(),獲得列值方法。Cursor遊標常用方法如下:
我們先來查一查使用者名稱為"Bor"的資訊:
db = ordersDBHelper.getReadableDatabase();// select * from Orders where CustomName = ‘Bor‘cursor = db.query(OrderDBHelper.TABLE_NAME, ORDER_COLUMNS, "CustomName = ?", new String[] {"Bor"}, null, null, null);if (cursor.getCount() > 0) { List<Order> orderList = new ArrayList<Order>(cursor.getCount()); while (cursor.moveToNext()) { Order order = parseOrder(cursor); orderList.add(order); } return orderList;}
當然我們也可以查詢總數、最大值最小值之類的,以查詢Country為China的使用者總數為例:
db = ordersDBHelper.getReadableDatabase();// select count(Id) from Orders where Country = ‘China‘cursor = db.query(OrderDBHelper.TABLE_NAME, new String[]{"COUNT(Id)"}, "Country = ?", new String[] {"China"}, null, null, null);if (cursor.moveToFirst()) { count = cursor.getInt(0);}
至此SQLite就介紹完了,大家可以下載Demo詳細查看。Demo中還有一些其他比較乾貨的東西,大家可以挖掘挖掘。當然Demo中也有些不足,我還會更新,盡量做到讓使用者通過Demo就能學會如何使用SQLite。
Android SQLite詳解