GreenDao数据库

本文详细介绍了如何配置和使用GreenDao数据库,包括在build.gradle中添加依赖,创建实体类,生成Dao文件,初始化数据库,以及在MainActivity中进行增删改查操作。
摘要由CSDN通过智能技术生成

如何配置GreenDao
1.在项目的build.grade的文件里加入一行代码
dependencies {
classpath ‘com.android.tools.build:gradle:3.2.0’
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.0’

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}

2.在App的build.grade的文件里加入代码
apply plugin: ‘org.greenrobot.greendao’

在android中添加
greendao {
schemaVersion 1//数据库版本号
daoPackage ‘jinyuanyuan.bw.com.greendaos.mygreendao’//设置DaoMaster、DaoSession、Dao包名
targetGenDir ‘src/main/java’//设置DaoMaster、DaoSession、Dao目录
//targetGenDirTest:设置生成单元测试目录
//generateTests:设置自动生成单元测试用例
}

3.导入依赖
implementation ‘org.greenrobot:greendao:3.2.2’

4.创建一个实体类
解析的数据中,找到你要找到的数据
加上 :@Entity

5.通过(make Project)锤出
1>DaoMaster
2>DaoSession
3>StudentDao

6.创建一个MyApp extends Application,在清单文件中注册(name)** 配置数据库 **
private static DaoSession mDaoSession;
@Override
public void onCreate() {
super.onCreate();
initGreenDao();
}
private void initGreenDao() {
//第一步创建OpenHelper类
DaoMaster.DevOpenHelper openHelper = new DaoMaster.DevOpenHelper(this, “lxx.db”);
//开启一个可写数据库类
SQLiteDatabase writableDatabase = openHelper.getWritableDatabase();
//通过DaoMaster封装
DaoMaster master = new DaoMaster(writableDatabase);
mDaoSession = master.newSession();
}

public static DaoSession getDaoSession() {
return mDaoSession;
}

7.在MainActivity中调用MyApp里面的方法
StudentDao dao = MyApp.getDaoSession().getStudentDao();

8.增删改查
//插入数据
private void insertStu() {
Student student = new Student(“李广强”, “丑八怪”, 38);
long insert = mStuDao.insert(student);
if (insert > 0) {
Toast.makeText(this, “插入成功”, Toast.LENGTH_SHORT).show();
}
}

//删除数据  删除必须要删除数据库里面存在的数据
private void deleteStu() {
    mStuDao.deleteByKey(1l);
    Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();
}

//修改数据
private void updateStu() {
    //修改必须要修改数据库里面存在的数据
    Student student = mStuDao.load(1l);
    student.setAge(3);
    student.setName("wwd");
    student.setSex("奇丑无比");
    mStuDao.update(student);
}

//查询数据
private void selectStu() {
    //查询所有数据
    GetContent.setText("");
    List<Student> students = mStuDao.loadAll();
    GetContent.setText(students.toString());
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值