框架学习系列二(数据库选型)

数据库选型框架

整理常用的数据库框架对比

  • Ormlite
  • GreenDao
  • Sugar
  • Realm
  • Sqlbrite

1.接入数据库:ormlite

gradle配置

compile 'com.j256.ormlite:ormlite-android:5.0'

工具类

public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
    private static final String TAG = DatabaseHelper.class.getSimpleName();
    public static final String DB_NAME = "autotest.db";
    private static final int DB_VERSION = 2;
    private static DatabaseHelper instance;
    public static synchronized DatabaseHelper getHelper() {
        if (instance == null) {
            synchronized (DatabaseHelper.class) {
                if (instance == null) {
                    instance = new DatabaseHelper(MyApplication.application);
                }
            }
        }
        return instance;
    }
    private DatabaseHelper(Context context) {
//        super(context, DB_NAME, context.getPackageName(), null, DB_VERSION, R.raw.ormlite_config);
        super(context, DB_NAME,  null, DB_VERSION);
    }
    @Override
    public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
        try {
            TableUtils.createTable(connectionSource, Repo.class);
        } catch (Exception e) {
            Log.e(TAG, "onCreate.. exception: "+e);
        }
    }
    @Override
    public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
        try {
            TableUtils.dropTable(connectionSource, Repo.class, true);
            onCreate(database, connectionSource);
        } catch (SQLException e) {
            Log.e(TAG, "onCreate.. exception: "+e);
        }
    }
    /**
     * 释放资源
     */
    @Override
    public void close() {
        super.close();
    }
}

实体类需要注解:

@DatabaseTable(tableName = "tb_repo")
public class Repo implements Serializable {
    @DatabaseField(generatedId = true)
    public long keyid;
    @DatabaseField(columnName = "id")
    public long id;
    @DatabaseField(columnName = "name")
    public String name;
    public Repo(){}
    public long getId() {
        return id;
    }
    public String getName() {
        return name;
    }
}

代码调用:

 //删除所有数据
TableUtils.clearTable(DatabaseHelper.getHelper().getConnectionSource(), Repo.class);
long currtime=System.currentTimeMillis();
final Dao simpleDao= DatabaseHelper.getHelper().getDao(Repo.class);
//插入100000条数据
simpleDao.callBatchTasks(new Callable() {
public Void call() throws Exception {
for (Repo t : list) {
simpleDao.create(t);
}
 return null;
 }
});
long endtime=System.currentTimeMillis();
//查询100000条数据
List list= simpleDao.queryForAll();
long endtime1=System.currentTimeMillis();
Log.d(TAG,"db:ormlite=,time="+(endtime-currtime)+",转化list="+(endtime1-endtime)+",ps:size="+list.size());
}catch (Exception e){
           Log.d(TAG,"db:ormlite="+e.getMessage());
}

2.接入数据库:greenDAO

Add the following Gradle configuration to your Android project:

// In your root build.gradle file:
buildscript {
    repositories {
        jcenter()
        mavenCentral() // add repository
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.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 {
    compile 'org.greenrobot:greendao:3.2.2' // add library
}

实体类:RepoGreen

@Entity(indexes = {
        @Index(value = "id,name DESC" , unique = true)
})
public class RepoGreen  {
    @Id
    public long keyid;
    @NotNull
    public long id;
    @NotNull
    public String name;
    public RepoGreen(){}
    @Generated(hash = 1374277050)
    public RepoGreen(long keyid, long id, @NotNull String name) {
        this.keyid = keyid;
        this.id = id;
        this.name = name;
    }
    public long getId() {
        return id;
    }
    public String getName() {
        return name;
    }
    public long getKeyid() {
        return this.keyid;
    }
    public void setKeyid(long keyid) {
        this.keyid = keyid;
    }
    public void setId(long id) {
        this.id = id;
    }
    public void setName(String name) {
        this.name = name;
    }
}

调用数据库

DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(DbActivity.this, "notes-db");
Database db = helper.getWritableDb();
DaoSession daoSession = new DaoMaster(db).newSession();
RepoGreenDao noteDao = daoSession.getRepoGreenDao();

增删查

//删除所有数据
   noteDao.deleteAll();
//插入数据
 noteDao.insertInTx(Addlist);
//查询条数据
List  list=queryList.list();

3. 接入数据库:sugar

gradle配置:

  //sugar数据库
  compile 'com.github.satyan:sugar:1.5'

出现问题:

E:\AndroidDeveloper\AndroidProject\git\Call\Automatic\AutoFramework\src\main\AndroidManifest.xml:13:9-36 Error:
    Attribute application@allowBackup value=(false) from AndroidManifest.xml:13:9-36
    is also present at [com.github.satyan:sugar:1.3] AndroidManifest.xml:12:9-35 value=(true).
    Suggestion: add 'tools:replace="android:allowBackup"' to  element at AndroidManifest.xml:11:5-36:19 to override.
E:\AndroidDeveloper\AndroidProject\git\Call\Automatic\AutoFramework\src\main\AndroidManifest.xml:14:9-43 Error:
    Attribute application@icon value=(@mipmap/ic_launcher) from AndroidManifest.xml:14:9-43
    is also present at [com.github.satyan:sugar:1.3] AndroidManifest.xml:13:9-45 value=(@drawable/ic_launcher).
    Suggestion: add 'tools:replace="android:icon"' to  element at AndroidManifest.xml:11:5-36:19 to override.

解决问题:

AndroidManifest配置修改:

xmlns:tools="http://schemas.android.com/tools"    这个必须添加

 tools:replace="android:allowBackup,android:icon"   这个必须添加

        

Application子节点添加:





实体类:

public class RepoSugar extends SugarRecord{
    public long keyid;
    public long id;
    public String name;
    public RepoSugar(long keyid, long id,  String name) {
        this.keyid = keyid;
        this.id = id;
        this.name = name;
    }
}

问题2:

no such table: REPO_SUGAR

解决方案:

2.1以上需要禁用Instant Run

4.数据库:realm 接入使用

Step 1: Add the class path dependency to the project level build.gradle file.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath "io.realm:realm-gradle-plugin:3.1.3"
    }
}

Step 2: Apply the realm-android plugin to the top of the application level build.gradle file.

apply plugin: 'realm-android'

Step 3:Entity

public class RepoRealm extends RealmObject {
    @Ignore
    public long keyid;
    public long id;
    public String name;

    public RepoRealm(){}
    public RepoRealm(long keyid, long id, String name) {
        this.keyid = keyid;
        this.id = id;
        this.name = name;
    }
}

Step 4:代码调用

 //初始化 Realm
Realm.init(DbActivity.this);
Realm realm = Realm.getDefaultInstance();
//删除所有数据
realm.beginTransaction();
realm.deleteAll();
realm.commitTransaction();
List addList=getRealmData();
long currtime=System.currentTimeMillis();
//插入十万条数据
realm.beginTransaction();
realm.insertOrUpdate(addList);
realm.commitTransaction();
long endtime=System.currentTimeMillis();
//查询十万条数据
RealmQuery query = realm.where(RepoRealm.class);
List list= query.findAll();
long endtime1=System.currentTimeMillis();
String value="db:Realm=,time="+(endtime-currtime)+",转化list="+(endtime1-endtime)+",ps:size="+list.size();

更多请参考官方api:realm

5.数据库:sqlbrite 接入使用

sqlbrite响应式数据库,执行原生的数据库操作
gradle配置

dependencies {
    //sqlbrite
    compile 'com.squareup.sqlbrite:sqlbrite:1.1.1'
}

工具类

public class DBHelper extends SQLiteOpenHelper {

    private static final String DBNAME = "sqlbrite.db";
    private static final int CURRENTVERSION = 1;
    public static final String USERTABLE = "repoSqlbriteTable";

    public DBHelper(Context context) {
        super(context, DBNAME, null, CURRENTVERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table if not exists " + USERTABLE + " ( _id integer primary key, idtest,name);");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

代码调用

//初始化 Realm
 SqlBrite sqlBrite = new SqlBrite.Builder().build();
DBHelper openHelper = new DBHelper(DbActivity.this);
 BriteDatabase db = sqlBrite.wrapDatabaseHelper(openHelper, Schedulers.io());
//删除所有数据
  db.delete(DBHelper.USERTABLE,null);
   final long currtime=System.currentTimeMillis();
//插入十万条数据

 for (int i=0;i() {
                        @Override
                        public void call(SqlBrite.Query query) {
                            Cursor cursor = query.run();
                            List list = new ArrayList();
                            while (cursor.moveToNext()) {
                                Repo repo=new Repo();
   String username = cursor.getString(cursor.getColumnIndex("name"));
   int kid = cursor.getInt(cursor.getColumnIndex("_id"));
 int idtest = cursor.getInt(cursor.getColumnIndex("idtest"));
    repo.setId(idtest);
         repo.setName(username);
         repo.setKeyid(kid);
          list.add(repo);
                            }
                            cursor.close();
                            long endtime1=System.currentTimeMillis();
       String value="db:Sqlbrite=,time="+(endtime-currtime)+",转化list="+(endtime1-endtime)+",ps:size="+list.size();
                            Log.d(TAG,value);
                            Message message=new Message();
                            message.what=5;
                            message.obj=value;
                            handler.sendMessage(message);
                        }
                    });

数据库性能对比数据

框架学习系列二(数据库选型)_第1张图片
这里写图片描述

相关demo请关注github/doublechina

你可能感兴趣的:(框架学习系列二(数据库选型))