一、项目配置

1、根目录下的build.gradle 中添加

maven { url "https://www.jitpack.io" }

如下:

99c90d8d3a3a35184d89b12e2c7c5e26.png

classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'

如下:

2368cc12c689db4db837f2df1746246e.png

2、app目录下的build.gradle 中添加

apply plugin: 'com.neenbedankt.android-apt'

def dbflow_version = "4.0.2"

依赖:

apt "com.github.Raizlabs.DBFlow:dbflow-processor:${dbflow_version}"

compile "com.github.Raizlabs.DBFlow:dbflow-core:${dbflow_version}"

compile "com.github.Raizlabs.DBFlow:dbflow:${dbflow_version}"

// sql-cipher database encyrption (optional)

compile "com.github.Raizlabs.DBFlow:dbflow-sqlcipher:${dbflow_version}"

3、创建自己的Application

public classXApplication extends Application{

@Overridepublic voidonCreate() {

super.onCreate();

FlowManager.init(this);

}

}

清单文件配置:

0d8ea028368b4b06096f11279b54b92d.png

二、使用

1、创建一个数据库类

/**

* @author xqx

* @email djlxqx@163.com

* blog:http://www.cnblogs.com/xqxacm/* createAt 2017/11/22

* description: 数据库类*/@Database(name= SchoolDatabase.Name , version =SchoolDatabase.VERSION)public classSchoolDatabase {static final String Name = "SchoolDB"; //数据库名

static final int VERSION = 1; //数据库版本号

}

2、创建一个表类

/**

* @author xqx

* @email djlxqx@163.com

* blog:http://www.cnblogs.com/xqxacm/* createAt 2017/11/22

* description: 学生表 属于SchoolDatabase数据库的*/@Table(database= SchoolDatabase.class)public classStudent extends BaseModel{//主键 一个表必须有至少一个主键//(autoincrement = true) 表示该字段是自增的,可以不设置 ,默认false

@PrimaryKey(autoincrement = true)longid ;//名字

@Column

String name;//年龄

@Columnintage;//---------------------以下为可有可无的---------------//

//注意 一定要有一个无参的构造方法

public Student() {

}

/**

* 构造方法 看情况添加 可不加

* @param name

* @param age*/

public Student(String name, intage) {this.name =name;this.age =age;

}//Getter 和 Setter 方法,自己添加、可有可无

public longgetId() {returnid;

}public void setId(longid) {this.id =id;

}publicString getName() {returnname;

}public voidsetName(String name) {this.name =name;

}public intgetAge() {returnage;

}public void setAge(intage) {this.age =age;

}

}

3、增删改查

Student student = newStudent();

student.setName("XQX");

student.setAge(18);

student.save();//保存

student.update();//更改

student.delete(); //删除

student.insert(); //添加

查询:

/**

* 查询年龄为100的学生记录

* @param age

* @return*/

public Student findSingleStudent(intage){

Student student= SQLite.select().from(Student.class).where(Student_Table.age.is(100)).querySingle();returnstudent;

}publicList getAllStudents(){

List students = SQLite.select().from(Student.class).queryList();returnstudents;

}

测试:

for (int i = 0; i < 10; i++) {

addStudent("学生:"+i , i);

}

List students = SQLite.select().from(Student.class).queryList();for (int i = 0; i < 10; i++) {

Log.i("xqxinfo","学生表中的所有记录:"+students.get(i).toString());

}

结果:

1eecb1b49c818072614156986fe45440.png

注意:如果一个表中的对象没有的话,save等同于insert都是添加记录

如果这个对象在表中存在,save即更新,不是添加

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐