0

多くの作業の後、私は最初のアプリを作成することができましたが、1 つの質問に固執します。私のアプリでは、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 にコンテンツをコピーしたい

それでは、いくつかの仮想テーブルを設定しましょう。

  • データベース バージョン 1 (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 は and のみをサポートADD COLUMNRENAME TOREMOVE COLUMNor 以外はサポートしません。したがって、テーブル全体を再作成する必要があります。

@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 に答える