【问题标题】:SQLite Connection GetConnection / ErrorSQLite 连接 GetConnection / 错误
【发布时间】:2023-03-06 23:58:01
【问题描述】:

我正在使用 Xamarin 和 Visual Studio 2017 构建跨平台应用程序。我的数据库连接出现问题。所以每次我启动我的应用程序时,它总是因为与数据库的连接而崩溃。这是我连接到数据库的代码。

public SQLiteConnection GetConnection()
{
    var filename = "database.db3";
    var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
    var path = Path.Combine(documentsPath, filename);

    var connection = new SQLiteConnection (new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid(), "database.db3", true);
    return connection;
}

任何建议我如何解决这个问题。
谢谢指教。

【问题讨论】:

  • 第四行的前三行有什么用?
  • 我即将包含路径变量而不是文件名。实际上我只是这样做了,但它不起作用。
  • 我认为您应该尝试捕获由您的代码引起的异常并报告收到的确切错误消息。显示的通用消息对调试应用程序没有帮助
  • 未处理的异常:SQLite.Net.SQLiteException: 消息“无法打开数据库文件:database.db3 (CannotOpen)”字符串
  • 尝试将第四行中的"database.db3" 替换为第三行中的path

标签: c# sqlite xamarin xamarin.ios xamarin.android


【解决方案1】:

我不确定 SQLite 在 Xamarin Forms 中的工作方式是否不同,但我使用 SQLite.NET(Frank Krueger 的)。根据您上面的示例,我所需要的只是使用您创建的路径变量;您创建了名为“path”的变量,但从未使用它打开连接。

以下是我如何在我的一个 Android(非表单)应用程序中执行此操作的示例。

    public string DBPath
    {
        get
        {
          return Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "dbName.sqlite");
        }
    }

然后我像这样创建 SQLiteConnection:

 using (var dbConnection = new SQLiteConnection(DBPath))
            {
             ...                    
            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多