Android数据库操作—— GreenDao让你的数据操作更简单

首先说下官网,官网对GreenDao的介绍是the best way to access sqlite(访问数据库的最好方式),诚如官网所言,GreenDao操作SqLite数据库十分方便,大多数情况下,仅仅只需一行简单代码就可完成增删改查等工作,而且这还是一个开源框架,完全免费

再说说优点:1.读写速度快
2.消耗资源少
3.很轻量
4.操作简单

先扔两个网站
greenDao官网
GreenDaoGitHub链接

下面我们一步一步使用GrennDao

第一步:集成

首先,先在项目的build.gradle文件中添加greendao插件工具

 classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'

然后在App文件下的build.gradle文件中引用插件并集成库

apply plugin: 'org.greenrobot.greendao' // apply plugin

dependencies {
    compile 'org.greenrobot:greendao:3.2.2' // add library
}

Sync Now
到此Greendao算是集成完成了

现在给你的数据库设置路径(省略不写,系统也会自动生成,不过为了方便查看,我们在这里配置下)

   greendao{
        //数据库schema版本,也可以理解为数据库版本号
        schemaVersion 1
        //设置DaoMaster 、DaoSession、Dao包名
        daoPackage 'com.test.testgreendao.greendao'
        //设置DaoMaster 、DaoSession、Dao目录
        targetGenDir 'src/main/java'
    }

第二步:建表

那这位看官改说了,库都没建怎么建表,您先消消气,慢慢看,后面就知道为啥建表了,咱们往下走

在这里先介绍几个GreenDao的几个名词

@Entity:告诉GreenDao该对象为实体,只有被@Entity注释的Bean类才能被dao类操作
@Id:对象的Id,使用Long类型作为EntityId,否则会报错。(autoincrement = true)表示主键会自增,如果false就会使用旧值
@Property:可以自定义字段名,注意外键不能使用该属性
@NotNull:属性不能为空
@Transient:使用该注释的属性不会被存入数据库的字段中
@Unique:该属性值必须在数据库中是唯一值
@Generated:编译后自动生成的构造函数、方法等的注释,提示构造函数、方法等不能被修改

知道名词后我们新建一个实体类

@Entity
public class StudentInfo {
    @Id(autoincrement = true)
    private Long id; //id  设置自增长
    private String name; //学生姓名
    private String grade;//学生年级
    private int score;//为了方便直接写成了整型

}

然后Make project,你会发现我们的实体类多出了很多东西,而这些东西都是GreenDao给我们生成的,我们无需做任何修改,如下图:
这里写图片描述

而且还多出来这三个文件

这里写图片描述

现在我们进行初始化数据库

  private void initGreenDao() {
        DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(this, "test.db", null);
        daoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());
        daoSession = daoMaster.newSession();
        studentInfoDao = daoSession.getStudentInfoDao();
    }

第三步:开搞

先修改一下界面,给界面添加几个按钮和一个Listview

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.test.testgreendao.MainActivity"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:orientation="horizontal">

        <Button
            android:id="@+id/add"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="增加数据"/>

        <Button
            android:id="@+id/del"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="删除数据"/>
        <Button
            android:id="@+id/update"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="修改数据"/>
        <Button
            android:id="@+id/check"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="查询数据"/>
    </LinearLayout>

    <ListView
        android:id="@+id/lvList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider="@color/colorAccent"
        android:dividerHeight="1dp" />
</LinearLayout>

增加一条数据
        StudentInfo studentInfo = new StudentInfo();
        studentInfo.setId(null);
        studentInfo.setName("张三");
        studentInfo.setGrade("三年级");
        studentInfo.setScore(80);
        studentInfoDao.insert(studentInfo);

点击增加数据,效果如下图

这里写图片描述

增加多条数据      
          //两个方法本质是一样的,只是插入的时间顺序有所区别,任取其一

        //方法一:循环插入数据
        for (int i = 0; i < 3; i++) {
            StudentInfo studentInfo = new StudentInfo();
            studentInfo.setId(null);
            studentInfo.setName("张三" + i);
            studentInfo.setGrade("三年级");
            studentInfo.setScore(80 + i);
            studentInfoDao.insert(studentInfo);
        }

        //方法二:一次插入多条数据
        List<StudentInfo> mList = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            StudentInfo studentInfo = new StudentInfo();
            studentInfo.setId(null);
            studentInfo.setName("李四" + i);
            studentInfo.setGrade("三年级");
            studentInfo.setScore(80 + i);
            mList.add(studentInfo);
        }
        studentInfoDao.insertInTx(mList);

点击增加按钮,效果如下图

这里写图片描述


查询所有数据

      List<String> mListData = new ArrayList<>();
        studentInfoList = studentInfoDao.queryBuilder().list();//为了方便显示我用listview承接,在列表中显示
        for (int i = 0; i < studentInfoList.size(); i++) {
            String data = "id:" + studentInfoList.get(i).getId() + ",name:" + studentInfoList.get(i).getName()
                    + ",Grade:" + studentInfoList.get(i).getGrade() + ",Score:" + studentInfoList.get(i).getScore();
            mListData.add(data);
        }
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                this, android.R.layout.simple_list_item_1, mListData);
        lvList.setAdapter(arrayAdapter);
        arrayAdapter.notifyDataSetChanged();

与上图相同

查询指定数据

//查询分数为八十的人员
 studentInfoList=studentInfoDao.queryBuilder().where(StudentInfoDao.Properties.Score.eq(80)).list();

如下图
这里写图片描述


更改一条id为2数据

  StudentInfo studentInfo =studentInfoDao.queryBuilder().
  where(StudentInfoDao.Properties.Id.eq(2)).build().unique();
        if (studentInfo != null) {
            studentInfo.setName("王五");
        }

如下图
这里写图片描述

删除一条数据

  //删除名字为李四1的学生
        studentInfoDao.queryBuilder().where(StudentInfoDao.Properties.Name.eq("李四1")).buildDelete().executeDeleteWithoutDetachingEntities();

结果如下图

这里写图片描述

删除所有数据

结果如下图
这里写图片描述

最后在扔几个链接:

demo地址
官网学习地址
GitHub分享地址

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值