DBFlow 浅显应用

DBFlow

特点:
1.基于SQLite数据库,SQLite数据库是轻量级数据库,受到广泛的应用。故DBFlow可以支持原生的sqlite语句查询;
2.增删改查比用原生数据库语句简单,方便使用;
3.开源;
github 地址

DBFlow快速上手:
1.在项目的gradle配置
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.0'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        maven { url "https://jitpack.io" }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

在APP的gradle配置
apply plugin: 'com.neenbedankt.android-apt'
def dbflow_version = "3.0.0-beta4"


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}"


在项目入口或者是application里面调用
FlowManager.init(this);初始化
 
  
建立数据库类
 
  
 
  
@Database( name = AppDateBase.DBNAME,version = AppDateBase.VERSION)
public class AppDateBase {

    public static final String DBNAME = "dateBase";

    public static final int VERSION = 1;
}

建立需要存储到数据库的对象
 
  
@Table(database = AppDateBase.class)
public class UserInfo extends BaseModel{
    @PrimaryKey(autoincrement = true)
    private long id;

    @Column
    private String userId;

    @Column
    private String name;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public long getId() {
        return id;
    }

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

 
}
注意:
建立的时候需要一个主键,并且各个属性是对外可见的,private 的话需要编写对应的get set 方法
 
  
剩下的就是增删改查了
 
  
 
  
UserInfo info = new UserInfo();
info.setName("哈哈哈哈~");
info.setUserId("123465");
//增
info.save();
//改(可加条件判断)
 
  
info.setName("hahahahah");
info.update();
//删
info.delete();
//查全部
List<UserInfo> userInfos = new Select().from(UserInfo.class).queryList();
 
  
查询的方法可参考 http://www.cnblogs.com/CharlesGrant/p/5520840.html

 
  
版本更新:
若没有更新(新增)对象属性的话就只需要把AppDateBase的版本号改下
若是有更新则需要写Migrations(测试时新增add字段)
 
  
@Migration(version = AppDateBase.VERSION, database = AppDateBase.class)
public class MigrationsUserInfo extends AlterTableMigration<UserInfo> {

    public MigrationsUserInfo(Class<UserInfo> table) {
        super(table);
    }

    @Override
    public void onPreMigrate() {
        addColumn(SQLiteType.TEXT, UserInfo_Table.add.getNameAlias().getName());
    }
}
 
  
 
  
 
  
 
 




猜你喜欢

转载自blog.csdn.net/u012977315/article/details/52174770