前篇已经介绍了基本的配置以及生成dao文件,这一篇将介绍针对数据库的几种操作。
- Application中初始化
private void setupDatabase() {
// 通过 DaoMaster 的内部类 DevOpenHelper,你可以得到一个便利的 SQLiteOpenHelper 对象。
// 可能你已经注意到了,你并不需要去编写「CREATE TABLE」这样的 SQL 语句,因为 greenDAO 已经帮你做了。
// 注意:默认的 DaoMaster.DevOpenHelper 会在数据库升级时,删除所有的表,意味着这将导致数据的丢失。
// 所以,在正式的项目中,你还应该做一层封装,来实现数据库的安全升级。
helper = new DaoMaster.DevOpenHelper(this, Constants.DB_NAME, null);
db = helper.getWritableDatabase();
// 注意:该数据库连接属于 DaoMaster,所以多个 Session 指的是相同的数据库连接。
daoMaster = new DaoMaster(db);
daoSession = daoMaster.newSession();
}
public DaoSession getDaoSession() {
return daoSession;
}
public SQLiteDatabase getDb() {
return db;
}
- 在activity中
1.查找所有
cursor = getDb().query(getNoteDao().getTablename(), getNoteDao().getAllColumns(), null, null, null, null, orderBy);
private NoteDao getNoteDao() {
// 通过 BaseApplication 类提供的 getDaoSession() 获取具体 Dao
return ((BaseApplication) this.getApplicationContext()).getDaoSession().getNoteDao();
}
private SQLiteDatabase getDb() {
// 通过 BaseApplication 类提供的 getDb() 获取具体 db
return ((BaseApplication) this.getApplicationContext()).getDb();
}
2.增加
private void addNote() {
String noteText = editText.getText().toString();
editText.setText("");
final DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
String comment = "Added on " + df.format(new Date());
if (noteText == null || noteText.equals("")) {
ToastUtils.show(getApplicationContext(), "Please enter a note to add");
} else {
// 插入操作,简单到只要你创建一个 Java 对象
Note note = new Note(null, noteText, comment, new Date());
getNoteDao().insert(note);
Log.d(TAG, "Inserted new note, ID: " + note.getId());
cursor.requery();
}
}
3.查询
private void search() {
String noteText = editText.getText().toString();
editText.setText("");
if (noteText == null || noteText.equals("")) {
ToastUtils.show(getApplicationContext(), "Please enter a note to query");
} else {
// Query 类代表了一个可以被重复执行的查询
Query query = getNoteDao().queryBuilder()
.where(NoteDao.Properties.Text.eq(noteText))
.orderAsc(NoteDao.Properties.Date)
.build();
// 查询结果以 List 返回
List notes = query.list();
ToastUtils.show(getApplicationContext(), "There have " + notes.size() + " records");
}
// 在 QueryBuilder 类中内置两个 Flag 用于方便输出执行的 SQL 语句与传递参数的值
QueryBuilder.LOG_SQL = true;
QueryBuilder.LOG_VALUES = true;
}
4.删除
getNoteDao().deleteByKey(id);
// getNoteDao().deleteAll();
ToastUtils.show(getApplicationContext(), "Deleted note, ID: " + id);
Log.d(TAG, "Deleted note, ID: " + id);
cursor.requery();