GreenDao自动生成Android数据库操作代码
16lz
2021-01-23
1、环境准备
1.1 jar包
1.2 生成器的代码
2、需要编写生重点内容成操作数据的代码
/**
* Generates entities and DAOs for the example project DaoExample.
*
* Run it as a Java application (not Android).
*
* @author Markus
*/
public class ExampleDaoGenerator {
public static void main(String[] args) throws Exception { //第一个为数据库的版本号,第二个是自动生成数据库相关文件的包名 Schema schema = new Schema(1000, "com.smartspyeye.livevideo.dao"); // 一旦你拥有了一个 Schema 对象后,你便可以使用它添加实体(Entities)了。 addNote(schema); // 最后我们将使用 DAOGenerator 类的 generateAll() 方法自动生成代码,此处你需要根据自己的情况更改输出目录这里我创建一个java-gen的文件夹。 new DaoGenerator().generateAll(schema, "../greendaoGenerator/src-gen");}private static void addNote(Schema schema) { //"HistoryMessage"与数据库对应的javabean对象 Entity note = schema.addEntity("HistoryMessage"); //设置主键字段 note.addIdProperty(); //设置Javabean属性与数据库SendUserName字段 note.addStringProperty("SendUserName"); //设置Javabean属性与数据库MsgCount字段 note.addStringProperty("MsgCount");}
3、执行步骤2,自动生成如下代码
4、编写数据库操作类的方法 增 删 改 查
public class AvPresenter {
public static final String dbName = "audioVideo.db";// public static final String dbName = "HistoryMessage.db";private DaoMaster.DevOpenHelper helper;private DaoMaster daoMaster;private DaoSession daoSession;private HistoryMessageDao historyMessageDao;public AvPresenter(Context context) { helper = new DaoMaster.DevOpenHelper(context, dbName, null); daoMaster = new DaoMaster(helper.getWritableDatabase()); daoSession = daoMaster.newSession();}public AvPresenter(Context context, String dbName) { helper = new DaoMaster.DevOpenHelper(context, dbName, null); daoMaster = new DaoMaster(helper.getWritableDatabase()); daoSession = daoMaster.newSession();}// 添加一条数据public long add(HistoryMessage hs) throws Exception { return daoSession.insertOrReplace(hs);}// 更新单条数据public void update(HistoryMessage hs) throws Exception { daoSession.update(hs);}// 查询所有数据public List loadHistoryMessageAll() throws Exception { return daoSession.getHistoryMessageDao().loadAll();}// 删除单条数据public void deleteHistoryMessage(HistoryMessage hs) throws Exception { daoSession.delete(hs);}// 删除所有数据public void deleteHistoryMessageAll() throws Exception { daoSession.deleteAll(HistoryMessage.class);}/** * 根据用户名条件查询用户信息,映射到Javabean对象 * * @param SendUserName * @return * @throws Exception */public HistoryMessage getMessageBySendUserName(String SendUserName)throws Exception { Query build = daoSession.queryBuilder(HistoryMessage.class).where(Properties.SendUserName.eq(SendUserName)).build(); List list = build.list(); return list.get(0);}public void close() { if (daoSession != null) { daoSession.clear(); daoSession = null; } if (helper != null) { helper.close(); helper = null; }}
}
更多相关文章
- Android 实现与Eclipse数据交互
- 可分享到 Android、iOS 和 Flutter平台的Rust代码编译 [转]
- Android拍照上传功能示例代码
- Android DEX反编译后部分代码解析
- Android之数据存入SD卡中
- Android get+post传值获取php服务端的json数据
- android 常用数据库字段描述
- android: 大量开源项目源代码分享