仅当Windows App 8.1中存在数据库时,Sqlite-net才会启动SQLiteConnection

Arg*_*rgh 1 c# database winrt-xaml sqlite-net

我想在我的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();

        }
Run Code Online (Sandbox Code Playgroud)

是否创建了数据库?

new SQLiteConnection(dbPath)调用时会创建空数据库.是否可以在不创建连接的情况下打开连接?

Vad*_*dim 5

如果您将查看您正在使用的构造函数的代码 -

public SQLiteConnection (string databasePath, bool storeDateTimeAsTicks = false)
            : this (databasePath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create, storeDateTimeAsTicks)
{
}
Run Code Online (Sandbox Code Playgroud)

您将看到它传入一个标志,指示SQLite创建数据库(如果它不存在).

要避免这种情况,只需使用另一个构造函数 -

public SQLiteConnection (string databasePath, SQLiteOpenFlags openFlags, bool storeDateTimeAsTicks = false)
Run Code Online (Sandbox Code Playgroud)

像这样 -

using (var db = new SQLiteConnection(dbPath, SQLiteOpenFlags.ReadWrite))
Run Code Online (Sandbox Code Playgroud)

请记住,如果数据库不存在,这将抛出SQLiteException.

另一种可能的解决方案是在打开之前手动检查文件是否存在.