首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Android:升级DB版本,添加新表

Android:升级DB版本,添加新表
EN

Stack Overflow用户
提问于 2011-11-15 16:45:56
回答 3查看 104.5K关注 0票数 120

我已经为我的应用程序创建了sqlite表,但现在我想向数据库中添加一个新表。

我更改了DB版本,如下所示

private static final int DATABASE_VERSION = 2;

并添加了用于创建表的字符串

private static final String DATABASE_CREATE_color = 
   "CREATE TABLE IF NOT EXISTS files(color text, incident_id text)";

onCreateonUpgrade如下:

@Override
    public void onCreate(SQLiteDatabase database) {
        database.execSQL(DATABASE_CREATE_incident);
        database.execSQL(DATABASE_CREATE_audio);
        database.execSQL(DATABASE_CREATE_video);
        database.execSQL(DATABASE_CREATE_image);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //drop table and add new tables when version 2 released.
        db.execSQL(DATABASE_CREATE_color);

    }

但是由于某些原因,新的表没有被创建。我做错了什么?

EN

回答 3

Stack Overflow用户

发布于 2011-11-15 16:51:14

您的代码看起来是正确的。我的建议是数据库已经认为它已经升级了。如果您在递增版本号之后执行项目,但在添加execSQL调用之前,测试设备/仿真器上的数据库可能已经认为它是版本2。

验证这一点的一种快速方法是将版本号更改为3 --如果在这之后升级,你就知道这只是因为你的设备认为它已经升级了。

票数 9
EN

Stack Overflow用户

发布于 2017-05-20 17:45:27

您可以使用SQLiteOpenHelper的onUpgrade方法。在onUpgrade方法中,您将获得oldVersion作为参数之一。

onUpgrade中使用switch,在每个case中使用版本号来跟踪数据库的当前版本。

最好是从oldVersion循环到newVersion,将version一次递增1,然后逐步升级数据库。当使用数据库版本1的人在很长一段时间后将应用程序升级到使用数据库版本7的版本,并且应用程序因为某些不兼容的更改而开始崩溃时,这是非常有用的。

然后,数据库中的更新将逐步完成,涵盖所有可能的情况,即将为每个新版本所做的更改合并到数据库中,从而防止您的应用程序崩溃。

例如:

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    switch (oldVersion) {
    case 1:
        String sql = "ALTER TABLE " + TABLE_SECRET + " ADD COLUMN " + "name_of_column_to_be_added" + " INTEGER";
        db.execSQL(sql);
        break;

    case 2:
        String sql = "SOME_QUERY";
        db.execSQL(sql);
        break;
    }

}
票数 2
EN

Stack Overflow用户

发布于 2017-12-24 05:20:10

@jkschneider的答案是正确的。然而,还有一种更好的方法。

按照链接https://riggaroo.co.za/android-sqlite-database-use-onupgrade-correctly/中的说明,为每次更新在sql文件中写入所需的更改。

from_1_to_2.sql

ALTER TABLE books ADD COLUMN book_rating INTEGER;

from_2_to_3.sql

ALTER TABLE books RENAME TO book_information;

from_3_to_4.sql

ALTER TABLE book_information ADD COLUMN calculated_pages_times_rating INTEGER;
UPDATE book_information SET calculated_pages_times_rating = (book_pages * book_rating) ;

这些.sql文件将根据数据库的版本在onUpgrade()方法中执行。

DatabaseHelper.java

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 4;

    private static final String DATABASE_NAME = "database.db";
    private static final String TAG = DatabaseHelper.class.getName();

    private static DatabaseHelper mInstance = null;
    private final Context context;

    private DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
    }

    public static synchronized DatabaseHelper getInstance(Context ctx) {
        if (mInstance == null) {
            mInstance = new DatabaseHelper(ctx.getApplicationContext());
        }
        return mInstance;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(BookEntry.SQL_CREATE_BOOK_ENTRY_TABLE);
        // The rest of your create scripts go here.

    }


    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.e(TAG, "Updating table from " + oldVersion + " to " + newVersion);
        // You will not need to modify this unless you need to do some android specific things.
        // When upgrading the database, all you need to do is add a file to the assets folder and name it:
        // from_1_to_2.sql with the version that you are upgrading to as the last version.
        try {
            for (int i = oldVersion; i < newVersion; ++i) {
                String migrationName = String.format("from_%d_to_%d.sql", i, (i + 1));
                Log.d(TAG, "Looking for migration file: " + migrationName);
                readAndExecuteSQLScript(db, context, migrationName);
            }
        } catch (Exception exception) {
            Log.e(TAG, "Exception running upgrade script:", exception);
        }

    }

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

    }

    private void readAndExecuteSQLScript(SQLiteDatabase db, Context ctx, String fileName) {
        if (TextUtils.isEmpty(fileName)) {
            Log.d(TAG, "SQL script file name is empty");
            return;
        }

        Log.d(TAG, "Script found. Executing...");
        AssetManager assetManager = ctx.getAssets();
        BufferedReader reader = null;

        try {
            InputStream is = assetManager.open(fileName);
            InputStreamReader isr = new InputStreamReader(is);
            reader = new BufferedReader(isr);
            executeSQLScript(db, reader);
        } catch (IOException e) {
            Log.e(TAG, "IOException:", e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    Log.e(TAG, "IOException:", e);
                }
            }
        }

    }

    private void executeSQLScript(SQLiteDatabase db, BufferedReader reader) throws IOException {
        String line;
        StringBuilder statement = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            statement.append(line);
            statement.append("\n");
            if (line.endsWith(";")) {
                db.execSQL(statement.toString());
                statement = new StringBuilder();
            }
        }
    }
}

在同一链接中还提供了一个示例项目:https://github.com/riggaroo/AndroidDatabaseUpgrades

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8133597

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档