2016-02-29 78 views
1

我有一个登录表单在我的项目,我写下面的代码附加我的数据库(存在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文件(但我把ddf和mdf都放在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)

+0

你有没有收到任何错误? –

+0

嗯,是的,基本的调试技巧真的很难得到。首先捕获异常并查看SQL Server日志以查看发生了什么。我很确定这个电话不会奇迹般地无所事事。 – TomTom

+0

@DynamicVariable问题已更新 – Ali

回答

1

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

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

+0

我该如何“将使用中的日志更改回NETWORK_SERVICE,然后将适当的权限应用于需要它的文件夹/文件” – Ali

+0

请参阅此链接,了解如何配置服务以“NETWORK SERVICE”身份运行:https:// technet.microsoft.com/en-us/library/cc755249.aspx。一旦你将它作为'NETWORK SERVICE'再次运行,那么你可以根据需要简单地将该用户添加到文件/文件夹权限中(我通常将它作为NETWORK_SERVICE添加到ACL中)。 – CodingGorilla

+0

我该如何编程? – Ali