DBflow数据库的简单使用

最近项目需要大量数据储存,最终选择了DBflow数据库.

对于DBflow数据库我就不做详细的赘述了,有兴趣的可以去官方看一下文档

官方文档: https://agrosner.gitbooks.io/dbflow/content/ 

第一步:

导入

  • build.gradle(Project)
    dependencies内添加以下内容。
    dependencies {
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.7'
    }
    
    
    allprojects {
      repositories {
        jcenter()
        maven { url "https://jitpack.io" }
      }
    }

     

  • build.gradle(app)
    apply plugin: 'com.neenbedankt.android-apt'
    def dbflow_version = "4.0.2"
    
    
    dependencies {
        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}"
    }

     

  • 第二步:

  • 初始化数据库

  • public class MyApp  extends Application {
        @Override
        public void onCreate() {
            super.onCreate();
            //初始化DBFLOW
            FlowManager.init(this);
        }
    }

    修改清单文件

  • //清单文件里添加 
    android:name=".MyApp"

    创建数据库

    @Database(name = AppDatabase.NAME, version = AppDatabase.VERSION)
    public class AppDatabase {
    
        // 数据库名称
        public static final String NAME = "AppDatabase";
    
        // 数据版本
        public static final int VERSION = 1;
    }

    创建表

  • @Table(database = AppDataBase.class)
    public class User2Model extends BaseModel {
    
        @PrimaryKey(autoincrement = true)
        private int id;
    
        @Column
        private String name;
    
        @Column
        private int age;
        @Column
        private int ages;
    
        @Column
        private long timeStamp;
    
        public int getAges() {
            return ages;
        }
    
        public void setAges(int ages) {
            this.ages = ages;
        }
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
    
    
    
        public void setAge(int age) {
            this.age = age;
        }
    
        public long getTimeStamp() {
            return timeStamp;
        }
    
        public void setTimeStamp(long timeStamp) {
            this.timeStamp = timeStamp;
        }
    }
    

    数据库 增 删 改 查 

  • 
    
    
           //插入数据  id 必须唯一
            User2Model userModel=new User2Model();
            userModel.setName("UserModel");
            userModel.setAge(1);
            userModel.insert();
    
            userModel=new User2Model();
            userModel.setName("UserModel");
            userModel.setAge(2);
            userModel.insert();
    
            userModel=new User2Model();
            userModel.setName("UserModel");
            userModel.setAge(3);
            userModel.insert();
    
            userModel=new User2Model();
            userModel.setName("UserModel");
            userModel.setAge(4);
            userModel.insert();
    
            userModel=new User2Model();
            userModel.setName("UserModel");
            userModel.setAge(5);
            userModel.insert();
    
            userModel=new User2Model();
            userModel.setName("UserModel");
            userModel.setAge(6);
            userModel.insert();
    
            SQLite.insert(User2Model.class)
                    .columns(User2Model_Table.name,User2Model_Table.age)
                    .values("angel",27)
                    .execute();
    
            //删除数据
            userModel = SQLite.select()
                    .from(User2Model.class)
                    .where(User2Model_Table.id.is(3))
                    .querySingle();
            if (userModel != null){
                userModel.delete();
            }
    
            SQLite.delete(User2Model.class)
                    .where(User2Model_Table.name.is("UserModel"))
                    .and(User2Model_Table.id.is(4))
                    .async()
                    .execute();
    
            //更新数据
                    userModel = SQLite.select()
                    .from(User2Model.class)
                    .where(User2Model_Table.id.is(1))
                    .querySingle();
            if (userModel != null){
                userModel.setName("update 1 ");
                userModel.update();
            }
    
            SQLite.update(User2Model.class)
                    .set(User2Model_Table.name.eq("update 2"))
                    .where(User2Model_Table.name.is("UserModel"))
                    .and(User2Model_Table.id.is(5))
                    .async()
                    .execute();
    
    
            //查询全部
            List<User2Model> noteBeans = SQLite.select()
                    .from(User2Model.class)
                    .queryList();
    
            //条件查询
            userModel = SQLite.select()
                    .from(User2Model.class)
                    .where(User2Model_Table.name.eq("update 2"))
                    .querySingle();
    

    事务、批量保存

  •   //异步事务
            FlowManager.getDatabase(AppDataBase.class).beginTransactionAsync(new ITransaction() {
                @Override
                public void execute(DatabaseWrapper databaseWrapper) {
                    for (int i=0;i<100;i++){
                        User2Model userModel=new User2Model();
                        userModel.setName("UserModel");
                        userModel.setAge(i);
                     
                        userModel.save(databaseWrapper);
                    }
                }
            }).success(new Transaction.Success() {
                @Override
                public void onSuccess(@NonNull Transaction transaction) {
    //                Log.e(TAG,"onSuccess()");
                }
            }).error(new Transaction.Error() {
                @Override
                public void onError(@NonNull Transaction transaction, @NonNull Throwable error) {
    //                Log.e(TAG,"onError()");
                }
            }).build().execute();
    
    

    数据库升级(增加表、增加字段等)

  • 如果是新增表无需做特别的处理,直接修改AppDatabase的版本号即可。

    如果需要新增字段,除了需要修改AppDatabase的版本号外,还需要做特殊的处理,DBFlow的描述是:Migrations。

    例子:对People新增一个ages字段

  • 第一步

  • @Database(name = AppDatabase.NAME, version = AppDatabase.VERSION)
    public class AppDatabase {
      //数据库名称
      public static final String NAME = "AppDatabase";
      //数据库版本号,这里修改2
      public static final int VERSION = 2;
    }
    第二步
  • @Table(database = AppDataBase.class)
    public class User2Model extends BaseModel {
    
        @PrimaryKey(autoincrement = true)
        private int id;
    
        @Column
        private String name;
    
        @Column
        private int age;
        @Column
        private int ages;
    
        @Column
        private long timeStamp;
    
        public int getAges() {
            return ages;
        }
    
        public void setAges(int ages) {
            this.ages = ages;
        }
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
    
    
    
        public void setAge(int age) {
            this.age = age;
        }
    
        public long getTimeStamp() {
            return timeStamp;
        }
    
        public void setTimeStamp(long timeStamp) {
            this.timeStamp = timeStamp;
        }
    }
    
    

    第三步:

  • 执行第二步之后,需要build(Android studio的build->Make Project、,通过apt更新People_Table,

  • 修改AppDataBase

  • 
    @Database(name = AppDataBase.NAME,version = AppDataBase.VERSION)
    public class AppDataBase {
        public static final String NAME="AppDataBase";
        public static final int VERSION=2;
    
        /**
         * 数据库的修改:
         * 1、PatientSession 表结构的变化
         * 2、增加表字段,考虑到版本兼容性,老版本不建议删除字段
         */
        @Migration(version = VERSION, database = AppDataBase.class)
        public static class Migration2UserData extends AlterTableMigration<User2Model> {
    
            public Migration2UserData(Class<User2Model> table) {
                super(table);
            }
    
            @Override
            public void onPreMigrate() {
                addColumn(SQLiteType.TEXT, "ages");
            }
        }
    }
    

     

  • 结束

 

 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值