更新apk版本后删除Android Sqlite数据库记录

时间:2014-06-02 04:23:10

标签: android sqlite orm

我尝试实现应用程序的持久层,以便在通过Google Play更新apk后,可以维护数据库记录。当它实现时,它会在更新我的apk版本后删除所有数据。你能告诉我备份和恢复sqlite记录的方法吗?

以下是我的代码

 private static final String DATABASE_NAME = "hkgadddlden.sqlite";

    private static final int DATABASE_VERSION = 6;

    private Dao<History, Integer> hDao = null;
    private Dao<Favourite, Integer> fDao = null;
    private Dao<Lm, Integer> lDao = null;
    private Dao<iconPlus, Integer> iDao = null;


    public DatabaseHelper(Context context)
    {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase database,ConnectionSource connectionSource)
    {
//      database.execSQL("create table history(t_id integer, topic text, page integer, PRIMARY KEY(t_id));");
//      database.execSQL("create table lm(t_id integer, PRIMARY KEY(t_id));");
//      database.execSQL("create table favourites(t_id integer, PRIMARY KEY(t_id));");

        try
        {
            TableUtils.createTable(connectionSource, History.class);
            TableUtils.createTable(connectionSource, Favourite.class);
            TableUtils.createTable(connectionSource, Lm.class); 
            TableUtils.createTable(connectionSource, iconPlus.class);            
        }
        catch (SQLException e)
        {
            Log.e(DatabaseHelper.class.getName(), "Can't create database", e);
            throw new RuntimeException(e);
        }
        catch (java.sql.SQLException e)
        {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db,ConnectionSource connectionSource, int oldVersion, int newVersion)
    {
        db.execSQL("DROP TABLE IF EXISTS history"); //刪除舊有的資料表
        db.execSQL("DROP TABLE IF EXISTS lm");
        db.execSQL("DROP TABLE IF EXISTS favourite");
        db.execSQL("DROP TABLE IF EXISTS iconPlus");        
        onCreate(db, connectionSource);

        try
        {
            List<String> allSql = new ArrayList<String>();
            for (String sql : allSql)
            {
                db.execSQL(sql);
            }
        }
        catch (SQLException e)
        {
            Log.e(DatabaseHelper.class.getName(), "exception during onUpgrade", e);
            throw new RuntimeException(e);
        }

    }

2 个答案:

答案 0 :(得分:2)

你的onUpgrade函数正在删除所有表。这意味着您将删除所有数据。如果您不想删除它们,则必须为每个可能的升级编写alter语句。

答案 1 :(得分:1)

如果要升级数据库版本,则必须使用检查

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
 if (oldVersion<2) {
// do upgrade from 1 to 2
 }

 if (oldVersion<3) {
// do upgrade from 2 to 3, which will also cover 1->3,
// since you just upgraded 1->2
 }

// and so on
 }

当您在db

中编写此代码时
    db.execSQL("DROP TABLE IF EXISTS history"); //刪除舊有的資料表
    db.execSQL("DROP TABLE IF EXISTS lm");
    db.execSQL("DROP TABLE IF EXISTS favourite");
    db.execSQL("DROP TABLE IF EXISTS iconPlus");        

它会丢弃你的表和数据