使用sqlite数据库和split -net改变模式



我目前在我的Windows Phone 8.1应用程序中使用SQLite数据库和SQLite- net库。我想知道是否有人对如何在应用程序版本之间升级时完成表模式更改有任何最佳实践。

我唯一的选择是手动创建原始SQL语句来更新模式吗?

作为对SO社区的小小感谢,我提供了用于处理模式更改的主代码。注意,这将处理从任何早期版本到最新版本的数据库升级(即使用户跳过两者之间的版本)。不处理数据库降级。我应该在try/catch语句中添加更多的错误检查。

在我的sqlite助手类中,我有以下声明:

private SQLiteConnection _db;
// Start from 1 and increment this number whenever DB schema changes are made
private const int LATEST_DATABASE_VERSION = 3;

那么我的主要升级方法是:

private void DoUpgradeDb(int oldVersion, int newVersion)
        {
            for (int vFrom = oldVersion; vFrom < newVersion; vFrom++)
            {
                switch (vFrom)
                {
                    case 1: // Upgrade from v1 to v2
                        UpgradeV1AlterPersonAddColumnAge();
                        UpgradeV1AnotherSchemaChange();
                        break;
                    case 2: // Upgrade from v2 to v3
                        UpgradeV2CreateTableHobbies();
                        break;
                    default:
                        break;
                }
            }
            // Save the new version number to local storage
            App.AppSettingsService.SetDatabaseVersion(newVersion);
        }
正如您在上面看到的,我喜欢将每个版本中所做的单独更改放入其自己的方法中,因此我可以将UpgradeV2CreateTableHobbies()方法定义为:
    private void UpgradeV2CreateTableHobbies()
    {
        _db.CreateTable<Hobbies>();
    }

当然,你也需要记住在从头创建数据库(例如新安装)时进行相同的模式更改,而不仅仅是在更新时。

下次需要升级时,可以增加LATEST_DATABASE_VERSION常数。每次实例化Sqlite helper类(因为我使用单例模式)时,我都会检查是否需要版本升级,您可以这样做:

    private bool UpgradeDbIfRequired()
    {
        bool wasUpgradeApplied = false;
        // I wrote a GetDatabaseVersion helper method that reads the version (as nullable int) from local app settings.
        int? currentVersion = App.AppSettingsService.GetDatabaseVersion();
        if (currentVersion.HasValue && currentVersion.Value < LATEST_DATABASE_VERSION)
        {
                // Upgrade to latest version
                DoUpgradeDb(currentVersion.Value, LATEST_DATABASE_VERSION);
                wasUpgradeApplied = true;
        }
        else
        {
            // Already on latest version
            return false;
        }
        return wasUpgradeApplied;
    }

最新更新