最近在做项目的时候,为了方便测试人员测试,在应用中加入正式库和测试库切换的功能。为了防止正式库和测试库切换带来的数据冲突,切换的时候必须把当前的数据库清空。代码如下:
package com.example.admin.greendaotest; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import com.greendao.gen.DaoMaster; import org.greenrobot.greendao.database.Database; /** * Created by admin on 2017/9/19. */ public class DBManager { private final static String dbName = "student_db"; private static DBManager mInstance; private DaoMaster.OpenHelper openHelper; private Context context; public DBManager(Context context) { this.context = context; openHelper = new DaoMaster.OpenHelper(context, dbName, null){}; } /** * 获取单例引用 * * @param context * @return */ public static DBManager getInstance(Context context) { if (mInstance == null) { synchronized (DBManager.class) { if (mInstance == null) { mInstance = new DBManager(context); } } } return mInstance; } /** * 获取可读数据库 */ private SQLiteDatabase getReadableDatabase() { if (openHelper == null) { openHelper = new MySQLiteOpenHelper(context, dbName, null); } SQLiteDatabase db = openHelper.getReadableDatabase(); return db; } /** * 获取可写数据库 */ private SQLiteDatabase getWritableDatabase() { if (openHelper == null) { openHelper = new MySQLiteOpenHelper(context, dbName, null); } SQLiteDatabase db = openHelper.getWritableDatabase(); return db; } public void deleSQL(){ SQLiteDatabase db=getWritableDatabase(); DaoMaster daoMaster = new DaoMaster(db); DaoMaster.dropAllTables(daoMaster.getDatabase(),true); DaoMaster.createAllTables(daoMaster.getDatabase(),true); } class MySQLiteOpenHelper extends DaoMaster.OpenHelper{ @Override public void onCreate(Database db) { super.onCreate(db); } public MySQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) { super(context, name, factory); } } }
必须要加上DaoMaster.createAllTables(daoMaster.getDatabase(),true),不然重新进行数据库操作的时候(crud)会报找不到数据库表的错误:Caused by: android.database.sqlite.SQLiteException: no such table: 表名 ,至于为什么不会重新创建数据库表,我也不知道为啥,在这上面也浪费了一些时间,所以写下这篇博客。