简体   繁体   English

SQLite 无法在 Xamarin.UWP 应用中打开数据库文件

[英]SQLite Could not open database file in Xamarin.UWP app

Sadly, the answer to the following question does not solve my problem: SQLite - Could not open database file遗憾的是,以下问题的答案并没有解决我的问题: SQLite - 无法打开数据库文件

I know that the folder exists, but still run into the following exception:我知道该文件夹存在,但仍然遇到以下异常:

SQLite.SQLiteException: 'Could not open database file: C:\\Users\\david\\data.db (CannotOpen)' SQLite.SQLiteException: '无法打开数据库文件:C:\\Users\\david\\data.db (CannotOpen)'

using (var conn = new SQLiteConnection(@"C:\Users\david\data.db"))
{
    conn.CreateTable<DBItem>();
    var item = new DBItem();
    item.TextData = addEntry.Text;
    conn.Insert(item);
}

I added this static Constants class to my project, as recommended here: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/data-cloud/data/databases我按照此处的建议将此静态常量类添加到了我的项目中: https : //docs.microsoft.com/en-us/xamarin/xamarin-forms/data-cloud/data/databases

public static class Constants
{
    public const string DatabaseFilename = "TodoSQLite.db3";

    public const SQLite.SQLiteOpenFlags Flags =
        // open the database in read/write mode
        SQLite.SQLiteOpenFlags.ReadWrite |
        // create the database if it doesn't exist
        SQLite.SQLiteOpenFlags.Create |
        // enable multi-threaded database access
        SQLite.SQLiteOpenFlags.SharedCache;

    public static string DatabasePath
    {
        get
        {
            var basePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
            return Path.Combine(basePath, DatabaseFilename);
        }
    }
}

And updated my calling code to the following:并将我的调用代码更新为以下内容:

using (var conn = new SQLiteConnection(Constants.DatabasePath))
{
    conn.CreateTable<DBItem>();
    var item = new DBItem();
    item.TextData = addEntry.Text;
    conn.Insert(item);
}

And it works now.它现在有效。 I had been following a slightly outdated tutorial that didn't mention this requirement.我一直在关注一个稍微过时的教程,它没有提到这个要求。

I'm still curious why I wasn't able to just simply use "C:\\Users\\david\\data.db"?我仍然很好奇为什么我不能简单地使用“C:\\Users\\david\\data.db”?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM