我目前在 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 帮助程序类时都会检查是否需要版本升级(因为我使用单例模式),您可以执行以下操作:
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;
}
关于sqlite - 使用 sqlite 数据库和 slite-net 进行架构更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24963402/