資料庫操作建議用ORM框架,簡單高效。這裡推薦xUtils,裡面包含DBUtils。github地址:https://github.com/wyouflf/xUtils
獲得資料庫例項建議用單例模式。
static DbUtils db = null; public static DbUtils getDb(Context context) { if (context == null) { context = DoctorApplication.getInstance(); } if (db == null) { db = DbUtils.create(context, "xUtils.db"); }); db.configAllowTransaction(true); return db; } db.configAllowTransaction(true); return db; }
建立一個實體類,對應資料庫中的表。
@Table(name = "User") public class User { private int id; //主鍵ID,必須 private String uid; private String type; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } }
查詢:
// 查詢,根據主鍵ID查詢 User userTemp = db.findById(User.class, user.getId()); List<User> list = db.findAll(User.class);//通過型別查詢,查詢所有 User user = db.findFirst(Selector.from(User.class).where("type","=","0")); // IS NULL User user = db.findFirst(Selector.from(User.class).where("type","=", null)); // IS NOT NULL User user = db.findFirst(Selector.from(User.class).where("type","!=", null));
List<User> list = db.findAll(Selector.from(User)
.where("id" ,"<", 54)
.and(WhereBuilder.b("id", ">", 20).or("id", " < ", 30))
.orderBy("id")
.limit(pageSize)
.offset(pageSize * pageIndex));
// op為"in"時,最後一個引數必須是陣列或Iterable的實現類(例如List等)
User test = db.findFirst(Selector.from(User.class).where("id", "in", new int[]{1, 2, 3}));
// op為"between"時,最後一個引數必須是陣列或Iterable的實現類(例如List等)
User test = db.findFirst(Selector.from(User.class).where("uid", "between", new String[]{"1", "5"}));
DbModel dbModel = db.findDbModelAll(Selector.from(User.class).select("uid"));//select("name")只取出name列
List<DbModel> dbModels = db.findDbModelAll(Selector.from(User.class).groupBy("type").select("uid", "count(uid)"));
...
List<DbModel> dbModels = db.findDbModelAll(sql); // 自定義sql查詢
db.execNonQuery(sql) // 執行自定義sql
//多條件混合查詢
List<User> userEnts = TCommUtil.getDb(this).findAll(Selector.from(User.class).where(WhereBuilder.b("id", ">", 5).or("id", "<", 3)).and("uid", "=", "0"));
//模糊查詢like
String str = "select id,nickname,age,gender,zhenduan,avatar,pid,type from User where uid = "
+ uid
+ " and type like '%"
+ value + "%'";
Cursor cursor = TCommUtil.getDb(this).execQuery(str);
cursor.moveToFirst();
for (int i = 0; i < cursor.getCount(); i++) {
User userEnt = new User();
userEnt.setId(cursor.getInt(0));
...
cursor.moveToNext();
}
cursor.close();
儲存
User userEnt = new User(); TCommUtil.getDb(this).save(user); List<User> userEnts = new ArrayList<User>(); TCommUtil.getDb(this).saveAll(userEnts);
刪除
TCommUtil.getDb(this).deleteAll(User.class); TCommUtil.getDb(this).delete(User.class, WhereBuilder.b("id", "=", 3));
修改
userEnt.setType("3"); TCommUtil.getDb(this).update(userEnt, WhereBuilder.b("id", "=", 0), "type");