編輯:關於 Android 程式設計
經過前面幾篇的鋪墊,增刪改三種操作我們都已經學完了。現在回頭看,用 LitePal 操作資料庫確實輕我已不少。但資料庫操作中真正最複雜、用法最多的,其實是查詢。LitePal 在這塊提供的 API 相當豐富,設計上也頗具巧思。這篇就專門來拆解查詢操作。
還沒看過前一篇的朋友,建議先參考〈Android 資料庫高手秘籍(六)——LitePal 的修改和刪除操作〉。
最原始的方式是直接寫 SQL,透過 SQLiteDatabase 的 rawQuery():
public Cursor rawQuery(String sql, String[] selectionArgs)
第一個參數是 SQL 字串,第二個是用來替換占位符(?)的字串陣列。回傳一個 Cursor,所有結果都封裝在裡面。
但多數人並不喜歡手寫 SQL,於是 Android 另外提供了封裝好的 query()。它有三個重載版本,參數最少的也有七個:
public Cursor query(String table, String[] columns, String selection,
String[] selectionArgs, String groupBy,
String having, String orderBy)
想查 news 表的全部資料,得這樣寫:
SQLiteDatabase db = dbHelper.getWritableDatabase(); Cursor cursor = db.query(news, null, null, null, null, null, null);
六個用不到的參數,全都得填 null。若加上條件——查詢評論數大於零的新聞:
Cursor cursor = db.query(news, null, "commentcount>?",
new String[]{ "0" }, null, null, null);
剩下的參數依舊只能填 null。
更麻煩的是,結果還得自己從 Cursor 逐一取出、再塞進實體類別:
List<News> newsList = new ArrayList<News>();
if (cursor != null && cursor.moveToFirst()) {
do {
int id = cursor.getInt(cursor.getColumnIndex("id"));
String title = cursor.getString(cursor.getColumnIndex("title"));
String content = cursor.getString(cursor.getColumnIndex("content"));
Date publishDate = new Date(cursor.getLong(cursor.getColumnIndex("publishdate")));
int commentCount = cursor.getInt(cursor.getColumnIndex("commentcount"));
News news = new News();
news.setId(id);
news.setTitle(title);
news.setContent(content);
news.setPublishDate(publishDate);
news.setCommentCount(commentCount);
newsList.add(news);
} while (cursor.moveToNext());
}
冗長的參數列表加上手工映射,就是傳統查詢的日常。你可能已經習慣了,但習慣是可以改變的。
LitePal 做了兩個關鍵改變:用連綴查詢取代冗長參數,以及直接回傳封裝好的物件而非 Cursor。
查詢 news 表中 id 為 1 的記錄:
News news = DataSupport.find(News.class, 1);
一行搞定,結果自動封裝成 News 物件。同樣的功能用原生寫法起碼要二十行。
find() 的第一個參數是泛型類別——傳入什麼類別,回傳就是什麼型別;第二個參數是 id 值。
News firstNews = DataSupport.findFirst(News.class); News lastNews = DataSupport.findLast(News.class);
傳統做法得在 SQL 裡指定 limit 再取第一筆,LitePal 直接提供了語意明確的方法。
想把 id 為 1、3、5、7 的資料一次取出:
List<News> newsList = DataSupport.findAll(News.class, 1, 3, 5, 7);
後面可以傳入任意個 id。若這些 id 已經在陣列裡:
long[] ids = new long[]{ 1, 3, 5, 7 };
List<News> newsList = DataSupport.findAll(News.class, ids);
而如果不指定任何 id,就是查詢整張表:
List<News> allNews = DataSupport.findAll(News.class);
值得留意的是,上面這幾種寫法其實呼叫的是同一個方法重載,靠可變參數達成多樣效果,語意卻依然清楚——這就是所謂的「查詢藝術」。
前面的用法都只能按 id 查詢。要自訂條件,LitePal 用連綴(chained calls)解決。
查詢評論數大於零的新聞:
List<News> newsList = DataSupport.where("commentcount > ?", 0).find(News.class);
等價的 SQL:
select * from news where commentcount > 0;
where() 的第一個參數是條件式,其後所有參數用來替換占位符。
只要 title 與 content 兩欄,再加上 select():
List<News> newsList = DataSupport.select("title", "content")
.where("commentcount > ?", 0)
.find(News.class);
select title, content from news where commentcount > 0;
按發布時間倒序排列,加上 order():
List<News> newsList = DataSupport.select("title", "content")
.where("commentcount > ?", 0)
.order("publishdate desc")
.find(News.class);
select title, content from news where commentcount > 0 order by publishdate desc;
asc 為正序,desc 為倒序。
只取前 10 筆,加上 limit():
List<News> newsList = DataSupport.select("title", "content")
.where("commentcount > ?", 0)
.order("publishdate desc")
.limit(10)
.find(News.class);
分頁時,第二頁要取第 11 到 20 筆,再加上 offset():
List<News> newsList = DataSupport.select("title", "content")
.where("commentcount > ?", 0)
.order("publishdate desc")
.limit(10)
.offset(10)
.find(News.class);
select title, content from news where commentcount > 0 order by publishdate desc limit 10, 10;
對比 query() 那串即使不用也得填 null 的參數,連綴查詢的優勢很明顯:需要什麼就接什麼,不需要的直接不寫。
LitePal 預設是「懶查詢」——不會順帶把關聯表的資料一起抓回來,這也是官方推薦的做法。若你確實想一次取回關聯資料,每個 find() 都有一個帶 isEager 參數的重載:
News news = DataSupport.find(News.class, 1, true); List<Comment> commentList = news.getCommentList();
寫法上只是在最後多帶一個 true。由於 comment 與 news 是多對一關聯,查一筆新聞時對應的評論也會一起被取出。
但這種方式官方並不推薦,原因有二:關聯表資料量大時查詢會很慢;而且無法繼續迭代——查不到「關聯表的關聯表」。
更好的做法是在模型類別中補一個方法,把查詢延後到真正需要時:
public class News extends DataSupport {
// ...
public List<Comment> getComments() {
return DataSupport.where("news_id = ?", String.valueOf(id))
.find(Comment.class);
}
}
這樣在需要評論時才呼叫 getComments(),既省資源也更好控制。
總會遇到連 API 也覆蓋不到的奇怪需求。LitePal 保留了逃生口 findBySQL():
Cursor cursor = DataSupport.findBySQL(
"select * from news where commentcount > ?", "0");
第一個參數是 SQL 語句,其後參數用於替換占位符,回傳 Cursor——與原生寫法一致。
LitePal 的查詢設計可以濃縮成三句話:
find(),多筆用 findAll(),兩端各有一對語意明確的輔助方法。select → where → order → limit → offset,用多少接多少。下一篇將開始講解聚合函數的用法。
https://github.com/LitePalFramework/LitePal
一步一步打造 Android 自訂帳號系統(一):讀取帳號與建立服務
使用 Android 手機時你會發現,有些應用(例如 QQ、微信、淘寶)為自己建立了帳號系統,並且能在設定頁面看到它。可是當自己想為 App 寫一套帳號系統時,總不知從何
Android 音訊開發(七):深入剖析 OpenSL ES API 的核心設計
這是《Android 音訊開發》系列文章的第七篇。上一篇已經從整體角度介紹了 OpenSL ES API 的基本概況,說明這個框架具備哪些特性、能做什麼、不能做什麼。本篇
深入解析 Android Service 的概念、生命週期與通訊
Service 是 Android 四大元件之一,是一種在後台執行、不與使用者直接互動的服務。它沒有介面,卻能在應用退出後依然存活,因而廣泛應用於音樂播放、資料定時更新等
Android 5.0 新特性解讀:Material Design 與開發環境搭建
概述 2014 年,Google 攜 Android 5.X 重裝歸來,全新的 UI 設計語言和更優化的性能,讓開發者眼前一亮。 安裝和配置 Android 5.0 開發