0

经过大量工作,我设法构建了我的第一个应用程序,但我坚持一个问题。对于我的应用程序,我使用的是 sql 数据库。假设我想将 30 条记录添加到某个表中。怎么可能当我在android市场上放一个新版本并带有一个新的sql表以供将来使用,但要保留以前数据库的记录?

它是否与以下内容有关:

@Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

编辑

我的数据库助手代码:

 public class DataBaseHelper extends SQLiteOpenHelper {


    private static String DB_PATH = "/data/data/com.test.com/databases/";
    private static String DB_NAME = "quizDb";
    private SQLiteDatabase myDataBase;
    private final Context myContext;
    private Cursor c;
    static int numberOfLevels = 10;
    private final static int DB_VERSION = 2; // = until level 10


    /**
     * Constructor Takes and keeps a reference of the passed context in order to
     * access to the application assets and resources.
     * 
     * @param context
     */
    public DataBaseHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
        this.myContext = context;

    }

    /**
     * Creates a empty database on the system and rewrites it with your own
     * database.
     * */
    public void createDataBase() throws IOException {

        boolean dbExist = checkDataBase();
        if (!dbExist) {
            // By calling this method and empty database will be created into
            // the default system path
            // of your application so we are gonna be able to overwrite that
            // database with our database.
            this.getReadableDatabase();

            try {
                copyDataBase();
            } catch (IOException e) {
                throw new Error("Error copying database");
            }
        }
    }

    /**
     * Check if the database already exist to avoid re-copying the file each
     * time you open the application.
     * 
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase() {
        File dbFile = new File(DB_PATH + DB_NAME);
        return dbFile.exists();
    }

    /**
     * Copies your database from your local assets-folder to the just created
     * empty database in the system folder, from where it can be accessed and
     * handled. This is done by transfering bytestream.
     * */
    private void copyDataBase() throws IOException {

        // Open your local db as the input stream
        InputStream myInput = myContext.getAssets().open(DB_NAME);

        // Path to the just created empty db
        String outFileName = DB_PATH + DB_NAME;

        // Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(outFileName);

        // transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }

        // Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();

    }

    public void openDataBase() throws SQLException {
        // Open the database
        String myPath = DB_PATH + DB_NAME;

        myDataBase = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READONLY);
    }

    @Override
    public synchronized void close() {
        if (c != null)
            c.close();
        if (myDataBase != null)
            myDataBase.close();

        super.close();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    public File getDatabasePath(String name) {

        File file = myContext.getDatabasePath(name);

        return file;
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("ATTACH DATABASE ? as AttachedDB",
                new String[] { getDatabasePath("quizDbNew").getPath() });
        db.execSQL("INSERT OR IGNORE INTO questions (_id, file, answer, level) SELECT _id, file, answer, level FROM AttachedDB.questions");
        db.execSQL("DETACH AttachedDB");

    }
4

1 回答 1

3

使用"DROP TABLE"in的概念onUpgrade()与数据库管理一样原始,但是更有用的技术需要更多的 SQL 知识。通过使用"ALTER TABLE"添加新列或以其他方式将旧数据整理到新架构中来升级数据库的更智能方法。


在您所说的评论中添加
以下内容(或多或少):

我想将我的 Db v1 备份文件中的内容复制到我当前的 Db v2

所以让我们建立几个假设的表格:

  • 数据库版本一 (DBv1):

    CREATE TABLE Foo(_id INTEGER PRIMARY KEY, bar TEXT, bar2 TEXT, bar3 TEXT);
    
  • 数据库版本 2 (DBv2):

    CREATE TABLE Foo(_id INTEGER PRIMARY KEY, bar2 TEXT, bar4 INTEGER);
    

首先让我们看看从 DBv1 到 DBv2 的定期升级。SQLite 仅支持ADD COLUMNand RENAME TO,不支持REMOVE COLUMN或其他任何东西。所以我们必须重新创建整个表:

@Override  // DBv1 => DBv2
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("ALTER TABLE Foo RENAME TO OldFoo");
    db.execSQL("CREATE TABLE Foo(_id INTEGER PRIMARY KEY, bar2 TEXT, bar4 INTEGER)");
    db.execSQL("INSERT INTO Foo (_id, bar) SELECT _id, bar2 FROM OldFoo");
    db.execSQL("DROP TABLE OldFoo");
}

这再次使用 DBv2 的模式创建了一个表,并通过将适当的列插入 DBv2 来保留 DBv1 中所有有效的现有数据。(然后它通过删除旧表来删除旧数据。)

您已经明智地选择在一个单独的文件中随着时间的推移备份您的数据库,但现在您希望将旧数据带入新的表模式。首先确保您的备份 SQLite 文件与您当前的 SQLite 文件 ( data/data/<reverse.package.name>/databases/) 位于同一目录中。它显然需要一个唯一的名称,我们称之为DBBackup。现在让我们附加DBBackup到您当前的数据库并从上面执行类似的操作:

// DBBackupv1 => DBv2
public void restore(SQLiteDatabase db) {
    db.execSQL("ATTACH DATABASE ? as AttachedDB", new String[] {getDatabasePath("DBBackup").getPath()});
    db.execSQL("INSERT OR IGNORE INTO Foo (_id, bar2) SELECT _id, bar2 FROM AttachedDB.Foo");
    db.execSQL("DETACH AttachedDB");
}

我曾经INSERT OR IGNORE恢复任何已删除但保持当前现有行不变的行。您可以使用INSERT OR REPLACE恢复到备份版本。还有更多选项可以满足您的需求。

于 2012-11-25T20:15:36.877 回答