只有当数据库存在于windows App 8.1中时,Sqlite才能启动SQLiteConnection
本文关键字:Sqlite 中时 SQLiteConnection 启动 数据库 存在 App windows | 更新日期: 2023-09-27 17:58:23
我想在我的Windows应用商店应用程序中读取一个sqlite数据库,如果它存在的话。。。
通常要从数据库中读取一个表,我会设置它所在的路径,然后调用SQLiteConnection函数。。。
问题是,当我调用像这样的简单函数时,为什么数据库不存在
public static async Task<ObservableCollection<Objects>> GetAll()
{
List<Objects> list;
using (var db = new SQLiteConnection(dbPath))
{
// Activate Tracing
db.Trace = true;
list = (from p in db.Table<Objects>()
select p).ToList();
}
创建数据库?
调用new SQLiteConnection(dbPath)
时会创建空数据库。可以在不创建连接的情况下打开连接吗?
如果您要查看正在使用的构造函数的代码-
public SQLiteConnection (string databasePath, bool storeDateTimeAsTicks = false)
: this (databasePath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create, storeDateTimeAsTicks)
{
}
您将看到它传递了一个标志,指示SQLite在数据库不存在的情况下创建数据库。
为了避免这种情况,只需使用另一个构造函数-
public SQLiteConnection (string databasePath, SQLiteOpenFlags openFlags, bool storeDateTimeAsTicks = false)
像这样-
using (var db = new SQLiteConnection(dbPath, SQLiteOpenFlags.ReadWrite))
请记住,如果数据库不存在,这将引发SQLiteException。
另一种可能的解决方案是在打开之前手动检查文件是否存在。
public async Task<bool> IsDbExists(string fileName)
{
try
{
var item = await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
var db = new SQLiteConnection("Your db path");
var tb1 = db.GetTableInfo("TableName1");
var tb2 = db.GetTableInfo("TableName2");
var tb3 = db.GetTableInfo("TableName3");
var tb4 = db.GetTableInfo("TableName4");
if (item == null || tb1.Count == 0 || tb2.Count == 0 || tb3.Count == 0 || tb4.Count == 0)
{
return false;
}
else
{
return true;
}
}
catch
{
return false;
}
}