greendao接入sql和android cursor的簡單應用
阿新 • • 發佈:2019-01-02
String sql="select PAYMENT_PAY_BY,sum(PAYMENT_MONEY) from PAYMENT where SYSTEM_BOOK_CODE = ? " + "and BRANCH_NUM= ? and SHIFT_TABLE_NUM=? and SHIFT_TABLE_BIZDAY=? group by PAYMENT_PAY_BY"; String[] strings = {systemBookCode,String.valueOf(branchNum),String.valueOf(shiftTableNum),shiftTableBizday}; Cursor cursor= paymentDao.getDatabase().rawQuery(sql, strings); if (cursor.moveToNext()){ AmountPay amountPay=new AmountPay(); amountPay.setName(cursor.getString(0)); amountPay.setAmountMoney(Float.parseFloat(cursor.getString(1))); amountPays.add(amountPay); }
參考文章:
https://blog.csdn.net/lpf0907/article/details/48444471
https://bbs.csdn.net/topics/392237448
cursor的簡單應用
- Cursor 是每行的集合。
使用 moveToFirst() 定位第一行。
- 你必須知道每一列的名稱。
- 你必須知道每一列的資料型別。
- Cursor 是一個隨機的資料來源。
- 所有的資料都是通過下標取得。
Cursor 的一些重要方法:
- close() 關閉遊標,釋放資源
- copyStringToBuffer(int columnIndex, CharArrayBuffer buffer)
在緩衝區中檢索請求的列的文字,將將其儲存 - getColumnCount() 返回所有列的總數
- getColumnIndex(String columnName) 返回指定列的名稱,如果不存在返回-1
- getColumnIndexOrThrow(String columnName) 從零開始返回指定列名稱,如果不存在將拋IllegalArgumentException 異常。
- getColumnName(int columnIndex) 從給定的索引返回列名
- getColumnNames() 返回一個字串陣列的列名
- getCount() 返回Cursor 中的行數
- moveToFirst() 移動游標到第一行
- moveToLast() 移動游標到最後一行
- moveToNext() 移動游標到下一行
- moveToPosition(int position) 移動游標到一個絕對的位置
- moveToPrevious() 移動游標到上一行
- 訪問 Cursor 的下標獲得其中的資料
cursor.moveToLast();
last = cursor.getInt(cursor.getColumnIndex("Id"));
Log.i("nowamagicdb", "last_id=>" + last);
- 迴圈 Cursor 取出我們需要的資料
複製程式碼
if (cursor.getCount() > 0) {
List<NowaMagic> myList = new ArrayList<NowaMagic> (cursor.getCount());
while (cursor.moveToNext()) {
myList.add(parse(cursor));
}
return myList;
}
當cur.moveToNext() 為假時將跳出迴圈,即 Cursor 資料迴圈完畢。
如果你喜歡用 for 迴圈而不想用While 迴圈可以使用Google 提供的幾下方法:
isBeforeFirst() 返回遊標是否指向之前第一行的位置
isAfterLast() 返回遊標是否指向第最後一行的位置
isClosed() 如果返回 true 即表示該遊戲標己關閉
有了以上的方法,可以如此取出資料:
for(cur.moveToFirst();!cur.isAfterLast();cur.moveToNext())
{
int nameColumn = cur.getColumnIndex(People.NAME);
int phoneColumn = cur.getColumnIndex(People.NUMBER);
String name = cur.getString(nameColumn);
String phoneNumber = cur.getString(phoneColumn);
}