以编程方式附加数据库 [英] Attach database programmatically

查看:29
本文介绍了以编程方式附加数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a login form in my project and I write below code to attach my database( there is in d:\ ) when this login form loads:

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:\ 中)

It works fine in my laptop. I publish my project (using c# publish) and install SQL Server and my project and copy my database in d:\ in another PC. but when i run my project, the database won't attach! I don't know why this problem occurrs... but I think maybe the reason is that I don't write any code to define *.ldf file (but i put both mdf and ldf file in d:\ )

错误:与 SQL Server 建立连接时发生与网络相关或特定于实例的错误.

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

未找到或无法访问服务器.验证实例名称是否正确以及 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.

(提供程序:命名管道提供程序,错误:40 - 无法打开与 SQL Server 的连接)

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

推荐答案

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

I would venture to guess this is a permissions issue, usually a freshly installed SQL Server is running a NETWORK_SERVICE which is a pretty low privilege account. It probably does not have access to the root of your G drive (or any part of it for that matter).

您可以通过将 servie 更改为以 LocalSystem 运行来非常快速地进行测试.一旦您确认这是一个问题,我建议将登录使用更改回 NETWORK_SERVICE,然后将适当的权限应用于需要它的文件夹/文件.

You can test this very quickly by changing the servie to run as LocalSystem. Once you've confirmed this as an issue I would recommend changing the log on use back to NETWORK_SERVICE and then applying the appropriate permissions to the folder/files that need it.

这篇关于以编程方式附加数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆