SQLite 是一個很棒的嵌入式關聯資料庫,但是開發卻非常費工,寫SQL是非常乏味冗長的任務,則greenDAO幫開發者做到這些事情,讓開發者能更專注於專案上其他問題。
greenDAO的主要設計目的:
- 最高效能
- API簡單好使用
- 高度優畫Android
- 低記憶體消耗
- 低Library Size (小於100k)
生成檔執行步驟:
- 建立Java module。
- 步驟1建立的Java module的gradle匯入library。
- 建立新的java檔,編寫DBSchema。
- 執行並創造生成檔。
![]() |
| 步驟1 |
compile 'de.greenrobot:greendao-generator:2.1.0' //步驟2
//步驟3
public class Mydaogenerator {
public static void main(String[] args) {
// DB版本號 , 目標 package name
Schema schema = new Schema(1, "tw.myself.oceanlin.dao");
createTable(schema);
generateDaoFiles(schema);
}
private static void createTable(Schema schema) {
//Entity 對應一個 DB table
Entity point = schema.addEntity("FunghiDialog");
//add table column
point.addIdProperty();
point.addDateProperty("date").notNull();
point.addStringProperty("text").notNull();
}
private static void generateDaoFiles(Schema schema) {
try {
DaoGenerator generator = new DaoGenerator();
//建立到指定目錄
generator.generateAll(schema, "../GCM_Test/app/src/main/java");
} catch (Exception e) {
e.printStackTrace();
}
}
}
![]() |
| 步驟4 |
| 自動生成檔 |
資料庫操作:
Gradle:
compile 'de.greenrobot:greendao:2.1.0'
建立一個DBHelper做操作。
public class DBHelper {
private static DBHelper INSTANCE = null;
private static final String DB_NAME = "funghidialog-db";
private DaoSession daoSession;
private AsyncSession asyncSession;
private DBHelper(Context context) {
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, DB_NAME, null);
DaoMaster daoMaster = new DaoMaster(helper.getWritableDatabase());
daoSession = daoMaster.newSession();
asyncSession = daoSession.startAsyncSession();
}
public static DBHelper getInstance(Context context){
if(INSTANCE == null)
INSTANCE = new DBHelper(context);
return INSTANCE;
}
public FunghiDialogDao getFunghiDao(){
return daoSession.getFunghiDialogDao();
}
}
新增資料(Insert):
FunghiDialog funghiDialog = new FunghiDialog(); funghiDialog.setText(msg); funghiDialog.setDate(new Date()); DBHelper.getInstance(this).getFunghiDao().insertOrReplace(funghiDialog);查詢資料(Select/Query):
此function寫在DBHelper。
public List撈取資料表內_id=1的資料。queryFunghiDialogs(String where, String... params) { List funghiDialogs = getFunghiDao().queryRaw(where, params); return funghiDialogs.size() > 0 ? funghiDialogs : null; }
List<FunghiDialog> getFunghiDialogs = DBHelper.getInstance(MainActivity.this).queryFunghiDialogs("WHERE _id == ?","1");
刪除資料(Delete):先撈出資料再刪除
DBHelper.getInstance(MainActivity.this).getFunghiDao().delete(getFunghiDialogs.get(getFunghiDialogs.size() - 1 - pos));更新資料(Update):
先撈出資料,對欲修改欄位做設定,再複寫就好。
funghidialog.setText("new data");
DBHelper.getInstance(this).getFunghiDao().insertOrReplace(funghiDialog);


沒有留言:
張貼留言