天天看點

greendao接入sql和android cursor的簡單應用

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 的一些重要方法:

  1. close() 關閉遊标,釋放資源
  2. copyStringToBuffer(int columnIndex, CharArrayBuffer buffer)

    在緩沖區中檢索請求的列的文本,将将其存儲

  3. getColumnCount() 傳回所有列的總數
  4. getColumnIndex(String columnName) 傳回指定列的名稱,如果不存在傳回-1
  5. getColumnIndexOrThrow(String columnName) 從零開始傳回指定列名稱,如果不存在将抛IllegalArgumentException 異常。
  6. getColumnName(int columnIndex) 從給定的索引傳回列名
  7. getColumnNames() 傳回一個字元串數組的列名
  8. getCount() 傳回Cursor 中的行數
  9. moveToFirst() 移動光标到第一行
  10. moveToLast() 移動光标到最後一行
  11. moveToNext() 移動光标到下一行
  12. moveToPosition(int position) 移動光标到一個絕對的位置
  13. moveToPrevious() 移動光标到上一行
  14. 通路 Cursor 的下标獲得其中的資料
cursor.moveToLast();

last = cursor.getInt(cursor.getColumnIndex("Id"));

Log.i("nowamagicdb", "last_id=>" + last);
           
  1. 循環 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);

}