標籤:
資料庫操作建議用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 NULLUser user = db.findFirst(Selector.from(User.class).where("type","=", null));// IS NOT NULLUser 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");
Android orm 架構xUtils簡介