利用greendao操作数据库时,都是以对象或者对象的list来进行增删改查的操作,操作的结果都是用一个list来接收的!!!
1.增加一条记录
Stu stu01=new Stu();
stu01.setStuID(11);
stu01.setStuName("张三");
stu01.setFlag(true);
stuDao().insert(stu01);
2.增加多条记录
List<Stu> list = new ArrayList<>();
Stu stu01=new Stu();
stu01.setStuID(11);
stu01.setStuName("张三");
stu01.setFlag(true);
list.add(stu01);
Stu stu02=new Stu();
stu02.setStuID(2);
stu02.setStuName("王五");
stu02.setFlag(true);
list.add(stu02);
Stu stu03=new Stu();
stu03.setStuID(Long.valueOf(5));
stu03.setStuName("李四");
stu03.setFlag(true);
list.add(stu03);
stuDao().insertInTx(list);
3.删除一条记录
(1)按对象删除
stuDao().delete(stu01);
(2)按主键删除(表中需建一个long类型的主键)
stuDao().deleteByKey(Long.valueOf(5));
4.删除多条记录(表中需建一个long类型的主键)
List<Stu> list = new ArrayList<>();
Stu stu01=new Stu();
stu01.setId(Long.valueOf(1));
stu01.setStuID(11);
stu01.setStuName("张三");
stu01.setFlag(true);
list.add(stu01);
Stu stu02=new Stu();
stu02.setId(Long.valueOf(2));
stu02.setStuID(2);
stu02.setStuName("王五");
stu02.setFlag(true);
list.add(stu02);
stuDao().deleteInTx(list);
5.全部删除
stuDao().deleteAll();
6.修改一条记录(表中需建一个long类型的主键)
Stu stu=stu01;
stu.setStuName("张小磊");
stuDao().update(stu);
7.修改多条记录
List<Stu> list = new ArrayList<>();
Stu stu=stu01;
stu.setStuName("张小磊");
list.add(stu);
stu=stu02;
stu.setStuName("招儿");
list.add(stu);
stuDao().updateInTx(list);
8.查询一条记录
根据一个字段查询另一个字段
public static String queryNameByID(long ID) {
List<Stu> stus = stuDao().queryRaw("where ID=?", String.valueOf(ID));
Stu stu = stus.get(0);
String name = stu.getName();
return name;
}
9.查询多条记录
(1)查询出当一个字段为多个值的情况下所有的记录
public static List<Stu> queryStus() {
List<Stu> stus = new ArrayList<>();
QueryBuilder queryBuilder = stuDao().queryBuilder();
queryBuilder.whereOr(StuDao.Properties.StuID.eq(2), StuDao.Properties.StuID.eq(3));
stus = queryBuilder.list();
return stus;
}
(2)对查询的记录进行升序(降序)排序
public static List<Stu> queryStus() {
List<Stu> stus = new ArrayList<>();
QueryBuilder queryBuilder = stuDao().queryBuilder();
queryBuilder.where(StuDao.Properties.Flag.eq(true)).orderAsc(StuDao.Properties.StuID);
stus = queryBuilder.list();
return stus;
}
(3)嵌套查询
public static List<Stu> queryStu() {
List<Stu> stus = new ArrayList<>();
QueryBuilder queryBuilder = stuDao().queryBuilder();
queryBuilder.where(StuDao.Properties.Flag.eq(true),
queryBuilder.or(StuDao.Properties.StuName.eq("张小磊"),
StuDao.Properties.StuName.eq("王五")));
stus = queryBuilder.list();
return stus;
}