继承自上一篇:
public List<Account> queryAll() { sqliteDatabase db = helper.getReadableDatabase(); Cursor c = db.rawQuery("SELECT * FROM account",null);// 查询表中所有的数据 List<Account> list = new ArrayList<Account>(); while (c.moveToNext()) { int id = c.getInt(c.getColumnIndex("_id")); String name = c.getString(c.getColumnIndex("name")); int balance = c.getInt(c.getColumnIndex("balance")); list.add(new Account(id,name,balance)); } c.close(); db.close(); return list; }
测试查询全部的方法:
public void testQueryAll(){ AccountDao dao = new AccountDao(getContext()); List<Account> list = dao.queryAll(); for (Account account : list) { System.out.println(account); } }
注意一下两种方式的区别:
String name = c.getString(0);// 从结果集中获取数据,直接拿的索引,这个索引 是0,因为在这个语句中:"SELECT name,balance FROM account WHERE _id=?" name的索引为0 int balance = c.getInt(c.getColumnIndex("balance"));// 从结果集中获取数据(先根据列名获取索引,再根据索引获取数据)原文链接:https://www.f2er.com/sqlite/200354.html