【问题标题】:Android - HELP moving away from builtin SQLite to OrmliteAndroid - 帮助从内置 SQLite 迁移到 Ormlite
【发布时间】:2015-11-10 08:07:53
【问题描述】:
我有一个在 Android 中创建的SQLite database,我手动管理所有代码以执行我的读写操作。我最近发现了ORMlite。从现在开始,我想使用ORMlite 来管理我的数据库。问题是应用程序已经在安卓市场上,我不希望我的用户丢失他们的数据。
有没有办法让ORMlite 开始管理已经创建的数据库?或者是否有一种标准做法可以从旧数据库中读取我的所有数据并将其写入新数据库?
【问题讨论】:
标签:
android
sqlite
database-migration
ormlite
【解决方案1】:
在做了相当多的尽职调查后,我意识到这是一项多么简单的任务。 Ormlite 实际上位于内置 SQLite 之上。无需代码即可移至Ormlite。我在Ormlite Helper Class 中简单地引用了我的数据库名称。
我的代码如下。我希望这对将来的其他人有所帮助。
public class OrmHelper extends OrmLiteSqliteOpenHelper {
private final String TAG = this.getClass().getSimpleName();
private Context context;
public OrmHelper(Context context) {
//references my Sqlite dbnames. I made them static in the SqlHelper class
super(context, DataBase.DB_Name, null, DataBase.DB_Version);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
try {
Log.i(TAG, "Creating database in Ormlite");
TableUtils.createTable(connectionSource, Model.class);
TableUtils.createTable(connectionSource, UserCredential.class);
} catch (SQLException e) {
Log.e(TAG, "Error creating database", e);
}
}
@Override
public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource,
int oldVersion, int newVersion) {
}
/**
* this genric method is for grabbing the Dao for any ormlite table
*/
public <T, V> Dao<T, V> getTypeDao(Class<T> classType, Class<V> idType)
throws SQLException{
return getDao(classType);
}
}