android 数据库存储之GreenDao的使用

1.GreenDao介绍
在项目开发过程中,涉及到存储,一般都用都SQlite,GreenDao是新出现的数据库,是一个对象关系映射(ORM)的框架,能够提供一个接口通过操作对象的方式去操作关系型数据库,它能够让你操作数据库时更简单、更方便
如图所示:
android 数据库存储之GreenDao的使用_第1张图片
2.GreenDao的优势
1.性能高,号称Android最快的关系型数据库
2.内存占用小
3.库文件比较小,小于100K,编译时间低,而且可以避免65K方法限制
4.支持数据库加密 greendao支持SQLCipher进行数据库加密 有关SQLCipher可以参考这篇博客Android数据存储之Sqlite采用SQLCipher数据库加密实战
5.简洁易用的API
3.项目地址
github:https://github.com/greenrobot/greenDAO
4.GreenDao的使用
1.添加依赖库
android 数据库存储之GreenDao的使用_第2张图片
2.建立映射类
android 数据库存储之GreenDao的使用_第3张图片
3.数据库管理类DBManager
private DaoMaster.DevOpenHelper openHelper;
private Context context;

public DBManager(Context context) {
    this.context = context;
    openHelper = new DaoMaster.DevOpenHelper(context, dbName, null);
}

/**
 * 获取单例引用
 *
 * @param context
 * @return
 */
public static DBManager getInstance(Context context) {
    if (mInstance == null) {
        synchronized (DBManager.class) {
            if (mInstance == null) {
                mInstance = new DBManager(context);
            }
        }
    }
    return mInstance;
}

}

4.数据库读取
private SQLiteDatabase getReadableDatabase() {
if (openHelper == null) {
openHelper = new DaoMaster.DevOpenHelper(context, dbName, null);
}
SQLiteDatabase db = openHelper.getReadableDatabase();
return db;
}
5
.数据库存储

private SQLiteDatabase getWritableDatabase() {
if (openHelper == null) {
openHelper = new DaoMaster.DevOpenHelper(context, dbName, null);
}
SQLiteDatabase db = openHelper.getWritableDatabase();
return db;
}

6.数据库插入
public void insertUser(User user) {
DaoMaster daoMaster = new DaoMaster(getWritableDatabase());
DaoSession daoSession = daoMaster.newSession();
UserDao userDao = daoSession.getUserDao();
userDao.insert(user);
}

7.数据库删除
public void deleteUser(User user) {
DaoMaster daoMaster = new DaoMaster(getWritableDatabase());
DaoSession daoSession = daoMaster.newSession();
UserDao userDao = daoSession.getUserDao();
userDao.delete(user);
}
8.查询数据库
/**
* 查询用户列表
*/
public List queryUserList() {
DaoMaster daoMaster = new DaoMaster(getReadableDatabase());
DaoSession daoSession = daoMaster.newSession();
UserDao userDao = daoSession.getUserDao();
QueryBuilder qb = userDao.queryBuilder();
List list = qb.list();
return list;
}

/**
 * 查询用户列表
 */
public List queryUserList(int age) {
    DaoMaster daoMaster = new DaoMaster(getReadableDatabase());
    DaoSession daoSession = daoMaster.newSession();
    UserDao userDao = daoSession.getUserDao();
    QueryBuilder qb = userDao.queryBuilder();
    qb.where(UserDao.Properties.Age.gt(age)).orderAsc(UserDao.Properties.Age);
    List list = qb.list();
    return list;
}

你可能感兴趣的:(android)