c# - 通过网络连接到 SQLite 数据库

标签 c# sqlite sqlconnection

我目前正在映射网络驱动器并以这种方式连接到文件 (Z:\Data\Database.db)。我希望能够在连接字符串中使用相对路径 (\server\Data\Database.db),但它给我一个 SQLite 错误“无法打开数据库文件”。 Directory.Exists(\\server\Data\Database.db); 检查返回 true。

这里尝试使用路径“\\server”作为参数打开连接:

public static OpenDB(string dbPath)
{
    using (SQLiteConnection conn = new SQLiteConnection($"Data Source={Path.Combine(dbPath, "Data\\Database.db")}"))
    {
        if (dbPath != null && dbPath != "")
        {
            try
            {
                conn.Open();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Unable to Open Database", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}

最佳答案

这是我使用的解决方案。它是来自 jdweng 的建议的组合和 Shawn .首先,我将路径 dbPath 设为管理共享驱动器。从那里我让程序从管理共享中创建数据库的临时本地副本:

private static void MakeTempDatabaseCopy(string dbPath, string exePath)
{
    try
    {
        File.Copy(Path.Combine(dbPath, "Data", "Database.db"), Path.Combine(exePath, "Temp", "Database.db"), true);
        FileInfo directoryInfo = new FileInfo(Path.Combine(exePath, "Temp", "Database.db"));
        directoryInfo.Attributes = FileAttributes.Temporary;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Error Retrieving Database", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

之后所有方法都可以从本地副本读取。由于 File.Copy() 使用 bool 值,任何需要刷新数据库的操作都可以使用来自管理共享的新副本覆盖本地副本。希望这对您有所帮助!

关于c# - 通过网络连接到 SQLite 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52119452/

相关文章:

c# - 将对象传递给 AutoMapper 映射

c# - 在 .NET 项目中包含 MediaFile 时遇到问题

android - 将 SQLite 添加到 Android NDK 项目

mysql - sql查询在slite +phonegap中不起作用(计算给定名称表中的元素数量)

python - Pandas to_sql 如何确定将哪个数据框列放入哪个数据库字段?

sql - 在经典 ASP 中,打开和关闭多个连接是否会对性能产生重大影响?

c# - 刷新 ModelState 以消除错误

c# - 单击 "Link"后 WPF Modern UI 弹出现代对话框

database - 打开一次数据库连接还是在每次数据库操作时打开?

c# - 创建现有 c# 类的扩展 'copy'