直接上DaoMaster
的代码
/** * WARNING: Drops all table on Upgrade! Use only during development. */
public static class DevOpenHelper extends OpenHelper {
public DevOpenHelper(Context context, String name, CursorFactory factory) {
super(context, name, factory);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.i("greenDAO", "Upgrading schema from version " + oldVersion + " to " + newVersion + " by dropping all tables");
dropAllTables(db, true);
onCreate(db);
}
}
注意看第一行注释:WARNING: Drops all table on Upgrade! Use only during development.
数据库升级的话,会删除所有表,然后重新创建。这种方式在开发期间,APP还没有上线之前是可以的。
当APP上线后,我们不能使用这种方式,因为这样会导致已经存在的数据会被删除。
需要我们写一个类来实现OpenHelper
onUpgrade
方法来自定义升级过程。 2.当然升级过程中也要修改DaoMaster.SCHEMA_VERSION
3.当DaoMaster.SCHEMA_VERSION
跟你当前数据库的版本比较后,
会根据你当前数据库的版本,然后进行升级。
4.关键代码onUpgrade
方法,会比较新数据库和旧数据库的版本,然后执行相应的sql升级:
/**
* Created by weijianxing on 9/22/15.
*/
public
class
SQLiteOpenHelper
extends
DaoMaster
.
OpenHelper
{
private
static
final
String
DB_NAME
=
"test.db"
;
private
static
final
SortedMap
<
Integer
,
Migration
>
ALL_MIGRATIONS
=
new
TreeMap
<>();
static
{
ALL_MIGRATIONS
.
put
(
1
,
new
V1Migration
());
ALL_MIGRATIONS
.
put
(
2
,
new
V2Migration
());
ALL_MIGRATIONS
.
put
(
3
,
new
V3Migration
());
}
public
SQLiteOpenHelper
(
Context
context
,
SQLiteDatabase
.
CursorFactory
factory
)
{
super
(
context
,
DB_NAME
,
factory
);
}
@Override
public
void
onCreate
(
SQLiteDatabase
db
)
{
super
.
onCreate
(
db
);
executeMigrations
(
db
,
ALL_MIGRATIONS
.
keySet
());
}
@Override
public
void
onUpgrade
(
SQLiteDatabase
sqLiteDatabase
,
int
oldVersion
,
int
newVersion
)
{
LogUtil
.
w
(
SQLiteOpenHelper
.
class
.
getSimpleName
(),
"Upgrade from"
+
oldVersion
+
"to"
+
newVersion
);
SortedMap
<
Integer
,
Migration
>
migrations
=
ALL_MIGRATIONS
.
subMap
(
oldVersion
,
newVersion
);
executeMigrations
(
sqLiteDatabase
,
migrations
.
keySet
());
}
private
void
executeMigrations
(
final
SQLiteDatabase
paramSQLiteDatabase
,
final
Set
<
Integer
>
migrationVersions
)
{
for
(
final
Integer
version
:
migrationVersions
)
{
ALL_MIGRATIONS
.
get
(
version
).
migrate
(
paramSQLiteDatabase
);
}
}
}
/**
* Created by weijianxing on 9/22/15.
*/
public
interface
Migration
{
void
migrate
(
SQLiteDatabase
db
);
}
/**
* Created by weijianxing on 9/22/15.
*/
public
class
V1Migration
implements
Migration
{
@Override
public
void
migrate
(
SQLiteDatabase
db
)
{
db
.
execSQL
(
"ALTER TABLE NOTE ADD COLUMN test"
);
}
}