Android原生数据库和GreenDao的简单使用

为什么要写这个文章呢,主要目的是做一个记录.

因为如果项目中如果用不到数据库的话,基本过段时间就忘记了.
当再需要用的时候,又得去查查查,浪费时间.

Android SQLite

1.创建SQLiteOpenHelper的子类

直接上代码

别看一丢代码就头大,其实这段代码比较简单,就是一个继承了 SQLiteOpenHelper的子类,有一个四个参数的构造器,然后实现了onCreate()onUpgrade()两个方法,至于这两个方法的作用,代码中已经有相应的注释了.

至于内部类 Builder, 相信知道建造者模式的一看就明白了.这只是为了创建实例的时候方便而已,不用也可以.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.TextUtils;

/**
* Created by chenmingliang on 2018/6/15.
*/

public class DatabaseHelper extends SQLiteOpenHelper {


/**
* @param context
* @param name 数据库名称
* @param factory 一个可选的游标工厂(通常是 null)
* @param version 当前数据库的版本,必须是整数并且是递增状态
*/
public DatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}



/**
* 数据库第一次创建的时候调用
* 也就是 第一次 getWritableDatabase() / getReadableDatabase()
* @param db
*
* 作用: 创建数据库/表并且初始化数据
*/
@Override
public void onCreate(SQLiteDatabase db) {

//创建一个 person 的表(id,name,address)
String sql = "create table person(id integer primary key autoincrement,name varchar(64),address varchar(64))";
db.execSQL(sql);
}

/**
* 数据库升级时自动调用即数据库版本发生变化的时候
* @param db
* @param oldVersion
* @param newVersion
*
* 作用:更新数据库表结构
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String sql = "alter table person add sex varchar(8)";
db.execSQL(sql);
}

public static final class Builder{
public static final String CONTEXT = "context";
public static final String NAME = "name";

private Context bContext;
private String bName;
private int bVersion;
public Builder context(Context context){
this.bContext = context;
return this;
}
public Builder databaseName(String name){
this.bName = name;
return this;
}
public Builder databaseVersion(int version){
this.bVersion = version;
return this;
}
public DatabaseHelper build(){

checkNotNull(bContext,CONTEXT);

if(TextUtils.isEmpty(bName))
checkNotNull(null,NAME);

if(0 == bVersion)
bVersion = 1;

return new DatabaseHelper(bContext,bName,null,bVersion);
}

private void checkNotNull(Object object,String type){
if(null == object){
String message = null;
switch (type){
case CONTEXT:
message = "context is not null in DatabaseHelper";
break;
case NAME:
message = "name is not null or empty in DatabaseHelper";
break;
default:
}
throw new NullPointerException(message);
}

}

}
}

2.具体使用

当我们有了 SQLiteOpenHelper 的子类后,我们就可以开始创建数据库创建表…操作了,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
private void database() {
//创建数据库 Helper 类
DatabaseHelper databaseHelper = new DatabaseHelper.Builder()
.context(this)
.databaseName("cml")
.build();

//这时候会真正的创建数据库
SQLiteDatabase database = databaseHelper.getWritableDatabase();

//增
String insertSql = "insert into person (id,name) values (1,'aaa')";
database.execSQL(insertSql);
String insertSql2 = "insert into person (id,name) values (2,'ccc')";
database.execSQL(insertSql2);

//改
String updateSql = "update [person] set name = 'aaa2' where id = 1";
database.execSQL(updateSql);

//删
String deleteSql = "delete from person where id = 2";
database.execSQL(deleteSql);

//查
Cursor cursor = database.rawQuery(" select * from person ", null);
if(cursor.moveToFirst()){
do {
String id = cursor.getString(cursor.getColumnIndex("id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
Log.e("Cml","person-->id:" +id+",name:" +name);
}while (cursor.moveToNext());
cursor.close();
}
}

好了,原生的简单用法就如上了,其中为了避免用 android 的方法传入过多的参数,就直接执行 sql 语句来进行数据的增删改查了,也建议这样做,可以有效的减少错误的发生.

GrennDao 的使用

github address

1.使用前配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// In your root build.gradle file:
buildscript {
repositories {
jcenter()
mavenCentral() // add repository
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.1'
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // add plugin
}
}

// In your app projects build.gradle file:
apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao' // apply plugin

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

greendao {
schemaVersion 1 // 数据库版本号
daoPackage "com.cml.myapplication.greendao" //自动生成文件的路劲(一般为包名+自定义文件夹名)
targetGenDir "src/main/java" //一般默认如此即可
}

2.创建实体类

使用注解

‘’’
@Entity
public class Person {
@Id
private long id;
private String name;
}

‘’’

然后Make Project 实体类就变成了如下(dao 自动为我们加了一些代码)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@Entity
public class Person {
@Id
private long id;
private String name;
@Generated(hash = 2039202055)
public Person(long id, String name) {
this.id = id;
this.name = name;
}
@Generated(hash = 1024547259)
public Person() {
}
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}

3.在 Application 中进行初始化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class MyApplication extends Application {

public static MyApplication mInstance;
private DaoSession mDaoSession;

@Override
public void onCreate() {
super.onCreate();
mInstance = this;
initDatabase();
}

public static MyApplication getApplication(){
return mInstance;
}


private void initDatabase() {
DaoMaster.DevOpenHelper openHelper = new DaoMaster.DevOpenHelper(this, "person");
SQLiteDatabase database = openHelper.getWritableDatabase();
DaoMaster daoMaster = new DaoMaster(database);
mDaoSession = daoMaster.newSession();
}

public DaoSession getDaoSession(){
return mDaoSession;
}

private void initAndfix() {
AndfixPatchManager.getInstance().initPatch(this);
}
}

ps:别忘记在 AndroidManifest.xml 中配置 application哦

4.具体使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
private void databaseWithDAO() {

long id = MyApplication.getApplication().getDaoSession().insert(new Person(0, "AAA"));

long id2 = MyApplication.getApplication().getDaoSession().insert(new Person(1, "BBB"));

MyApplication.getApplication().getDaoSession().update(new Person(0,"AAA2"));

MyApplication.getApplication().getDaoSession().delete(new Person(1,"BBB"));

List<Person> people = MyApplication.getApplication().getDaoSession().loadAll(Person.class);

for(Person p : people){
Log.e("Cml","person -->id: "+p.getId()+", name: "+p.getName());
}
}

至此dao的简单使用就完成了.