为避免创建双重SQLite DB,如何检测是否已存在?
1)下面的代码是在App.xaml.cs中创建SQLite DB
2)App.xaml.cs中的代码是创建SQLite DB还是只创建Table或BOTH?
3)在MainPage中,如何创建SQLite DB,如何再次检查。
问题: 没有错误消息和MainPage没有显示。
感谢您的帮助。感谢
-- In below checking rootFrame in App.xaml.cs if (rootFrame == null) { //-- Detect before creating bool result = await GetIfFileExistsAsync(DBPath); if (result == true) { MessageDialog mError = new MessageDialog("DB Created", "DB creation status"); await mError.ShowAsync(); return; } else { MessageDialog mError = new MessageDialog("DB NOT Created", "NO DB created"); await mError.ShowAsync(); CreateDBNow(); } //---- rootFrame } private async Task GetIfFileExistsAsync(string strDBPath) { try { var dbFile = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(strDBPath); if (dbFile != null) { return true; } else { return false; } } catch (FileNotFoundException) { return false; } } private async void CreateDBNow() { DBPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "customers.sqlite"); using (var db = new SQLite.SQLiteConnection(DBPath)) { // Create the tables if they don't exist db.CreateTable(); } MessageDialog mError = new MessageDialog("DB now created", "DB created"); await mError.ShowAsync(); } --- in MainPage
I need to check one more time if SQLite DB is created.
答案 0 :(得分:0)
作为开发人员将数据库存储在本地文件夹中的最佳实践,所以下面给出的方便方法将对您有所帮助。 WinRT没有检查文件是否存在的功能。因此,这不仅适用于检查数据库文件,还适用于所有StorageFile
。
public async Task<bool> IsDatabaseExistsAsync(string DatabaseNameWithExtension)
{
try
{
var dbFile = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(DatabaseNameWithExtension);
return true;
}
catch (Exception)
{
return false;
}
}