前言
年前做了一個訪問通訊錄的需求,需要將用戶的通訊錄存入本地數(shù)據(jù)庫中,以前用過原生的SQLite數(shù)據(jù)庫,但是需要自己封裝,自己寫sql語句,所以這次需求找了一個數(shù)據(jù)庫框架使用GreenDao,仔細找了一下發(fā)現(xiàn) Android 平臺上的數(shù)據(jù)庫框架可真夠多,但是有一個共同特點就是基于對象關(guān)系映射模型的。實現(xiàn)的目標也都是不需要寫 SQL 語句,通過對對象的操作保存和操作數(shù)據(jù)。要是從語法的簡潔性來說都有自己的特點,總的來說不相上下。
下面來說一下GreenDao數(shù)據(jù)庫的優(yōu)勢
1.存取速度快;
2.支持數(shù)據(jù)庫加密;
3.輕量級;
4.激活實體;
5.支持緩存;
6.代碼自動生成;
總結(jié):效率很高,插入和更新的速度是sqlite的2倍,加載實體的速度是ormlite(也是一個數(shù)據(jù)庫框架)的4.5倍,目前git上一直在做更新維護,start數(shù)量為9000多。
下面我們言簡意賅,主要說下GreenDao數(shù)據(jù)庫的使用。
一、GreenDao數(shù)據(jù)庫的使用
第一步: 在項目的.gradle文件里面添加
buildscript {
repositories {
jcenter()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
classpath 'org.greenrobot:greendao-gradle-plugin:3.1.0'
}
}
第二步:在moddle的.gradle文件里面添加
android {
greendao {
schemaVersion 1
daoPackage 'com.jyjt.ydyl.greendao.gen'
targetGenDir 'src/main/java'
}
}
依賴里面添加
compile 'org.greenrobot:greendao:3.1.0'
compile 'org.greenrobot:greendao-generator:3.1.0'
第三步: 添加Bean類,用User舉例子 , 一定要記得注解@Entity 如:
@Entity
public class PhoneContactsEntity {
@Id(autoincrement = true)
private Long id;
//姓名
public String name = "";
//電話
public String phone = "";
//聯(lián)系人id
public String contactsId = "";
//電話和姓名
public String phoneName = "";
}
第四步:編譯項目,PhoneContactsEntity實體類會自動編譯,生成get、set方法并且會在com.jyjt.ydyl.greendao.gen目錄下生成三個文件;

第五步:Application中進行初始化,創(chuàng)建表;
import android.app.Application;
import android.database.sqlite.SQLiteDatabase;
import com.example.john.greendaodemo.gen.DaoMaster;
import com.jyjt.ydyl.greendao.gen.DaoSession;
public class AppApplication extends Application {
private DaoMaster.DevOpenHelper mHelper;
private SQLiteDatabase db;
private DaoMaster mDaoMaster;
private DaoSession mDaoSession;
public static AppApplication instances;
@Override
public void onCreate() {
super.onCreate();
instances = this;
setDatabase();
}
/**
* 單例模式 * *
*/
public static AppApplication getInstances() {
return instances;
}
/* 通過 DaoMaster 的內(nèi)部類 DevOpenHelper,你可以得到一個便利的 SQLiteOpenHelper 對象。
可能你已經(jīng)注意到了,你并不需要去編寫「CREATE TABLE」這樣的 SQL 語句,因為 greenDAO 已經(jīng)幫你做了。 注意:默認的 DaoMaster.DevOpenHelper 會在數(shù)據(jù)庫升級時,刪除所有的表,意味著這將導致數(shù)據(jù)的丟失。*/
private void setDatabase() {
mHelper = new DaoMaster.DevOpenHelper(this, "notes-db", null);
db = mHelper.getWritableDatabase(); mDaoMaster = new DaoMaster(db);
mDaoSession = mDaoMaster.newSession();
}
public DaoSession getDaoSession() {
return mDaoSession;
}
public SQLiteDatabase getDb() {
return db;
}
}
第六步:對表的具體操作;
public class SQLiteUtils {
private static SQLiteUtils instance;
PhoneContactsEntityDao phoneContactsEntityDao;
DaoSession daoSession;
private SQLiteUtils() {
phoneContactsEntityDao = MyApplication.getmApplication().getDaoSession().getPhoneContactsEntityDao();
daoSession = MyApplication.getmApplication().getDaoSession();
}
public static SQLiteUtils getInstance() {
if (instance == null) {
synchronized (SQLiteUtils.class) {
if (instance == null) {
instance = new SQLiteUtils();
}
}
}
return instance;
}
//增加
public void addContacts(PhoneContactsEntity testBean) {
phoneContactsEntityDao.insert(testBean);
}
//刪除
public void deleteContacts(PhoneContactsEntity testBean) {
phoneContactsEntityDao.delete(testBean);
}
//修改
public void updateContacts(PhoneContactsEntity testBean) {
phoneContactsEntityDao.update(testBean);
}
//條件查詢
public List selectAllContacts() {
phoneContactsEntityDao.detachAll();//清除緩存
List list1 = phoneContactsEntityDao.queryBuilder().where(PhoneContactsEntityDao.Properties.LogingId.eq(ConfigUtils.getUid())).build().li st();
return list1 == null ? new ArrayList() : list1;
}
//刪除表中內(nèi)容
public void deleteAllContact() {
phoneContactsEntityDao.deleteAll();
}
二、where 和whereOr的使用
whereOr :或條件查詢 多個或用“,”分隔
where:和條件查詢 多個和用“,”分隔
例如:當前用戶,展示狀態(tài) 查詢用戶手機號碼或姓名中包含有關(guān)鍵字的人
List list = phoneContactsEntityDao.queryBuilder().whereOr(PhoneContactsEntityDao.Properties.Phone.like("%" + key + "%"),PhoneContactsEntityDao.Properties.Name.like("%" + key + "%")).where(PhoneContactsEntityDao.Properties.IsShow.eq("1"), PhoneContactsEntityDao.Properties.LogingId.eq(ConfigUtils.getUid())).build().list();
三.GreeDao使用sql語句
當然有可能需求復雜的時候GreenDao提供的api實現(xiàn)不了你的需求,但是GreeDao支持使用sql語句,下面是通訊錄項目中用到的sql語句
String sql = "update `" + talbelName + "` set `USER_SATE` = '1' where `LOGING_ID` = '" + ConfigUtils.getUid() + "' and PHONE='" + upSateContacts.get(i).getPhone() + "'";
String sql = "delete from `" + talbelName + "` where `LOGING_ID` = '" + ConfigUtils.getUid() + "'";
String sql = "update `" + talbelName + "` set `IS_SHOW` = '0' where `LOGING_ID` = '" + ConfigUtils.getUid() + "' and PHONE IN (" + phone + ")";
daoSession.getDatabase().execSQL(sql);
四、sql語句
下面讓我們來具體溫習下SQL語句
1、查詢數(shù)據(jù)
select * from table1 where 范圍;
2、插入數(shù)據(jù)
insert into table1(field1,field2) values(value1,value2);
3、刪除數(shù)據(jù)
delete from table1 where 范圍;
4、更新數(shù)據(jù)
update table1 set field1=value1, field2=value2 where 范圍;
5、模糊查詢
select * from table1 where field1 like ’%value1%’;
6、排序
select * from table1 order by field1,field2 [desc];
7、分頁查詢(limit 要放到最后)
select * from table1 where 范圍 limit 0,10;
8、求總數(shù)
select count as totalcount from table1;
9、求和
select sum(field1) as sumvalue from table1;
10、求平均數(shù)
select avg(field1) as avgvalue from table1;
11、求最大
select max(field1) as maxvalue from table;
12、求最小
select min(field1) as minvalue from table1;