c# - 以编程方式附加数据库

标签 c# sql-server winforms

我的项目中有一个登录表单,当加载此登录表单时,我编写以下代码来附加我的数据库(位于 d:\中):

try
{ 
    SqlConnection con = new SqlConnection(@"Data Source=.;Initial Catalog=master;Integrated Security=True");
    con.Open();

    SqlDataAdapter da = new SqlDataAdapter("select name from sys.databases", con);
    DataTable dt = new DataTable();
    da.Fill(dt);

    string[] array = dt
        .AsEnumerable()
        .Select(row => row.Field<string>("Name"))
        .ToArray();

    if (!array.Contains("cstmrDB", StringComparer.OrdinalIgnoreCase))
    {
        SqlCommand cmd = new SqlCommand("sp_attach_db");
        cmd.Connection = con;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@dbname", "Apdb");
        cmd.Parameters.AddWithValue("@filename1", @"d:\Apdb.mdf");
        cmd.ExecuteNonQuery();

    }
}
catch (exception ex) 
{ 
    messagebox.show(ex.message); 
}

它在我的笔记本电脑上运行良好。我发布我的项目(使用 c# 发布)并安装 SQL Server 和我的项目,并将我的数据库复制到另一台 PC 的 d:\中。但是当我运行我的项目时,数据库不会附加!我不知道为什么会出现这个问题...但我想原因可能是我没有编写任何代码来定义 *.ldf 文件(但我将 mdf 和 ldf 文件都放在 d:\中)

ERROR: A network-related or instance-specific error occurred while establishing a connection to SQL Server.

The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.

(provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

最佳答案

我大胆猜测这是一个权限问题,通常新安装的 SQL Server 正在运行 NETWORK_SERVICE,这是一个权限相当低的帐户。它可能无法访问您的G驱动器的根目录(或其任何部分)。

您可以通过将服务更改为作为 LocalSystem 运行来快速测试这一点。一旦您确认这是一个问题,我建议您将登录使用更改回 NETWORK_SERVICE,然后对需要它的文件夹/文件应用适当的权限。

关于c# - 以编程方式附加数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35700066/

相关文章:

c# - 如何高效避免重复键异常

c# - 如何通过 Windows 应用商店分发 DeskBand

sql-server - 在 SQL Server 2008 中实现行级安全性

sql - 通过删除执行计划中的排序运算符来优化 SQL 查询

c# - C#中的目录路径

C# 随机消失的用户控件

c# - 如何使 EntityFramework 关系可查询?

c# - Ninject Web 应用程序 : All bindings should be InRequestScope()?

c# - 存储数据并访问它

c# - 使属性只能通过绑定(bind)的编辑器(组件)进行编辑