我有一个登录表单在我的项目,我写下面的代码附加我的数据库(存在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)
你有没有收到任何错误? –
嗯,是的,基本的调试技巧真的很难得到。首先捕获异常并查看SQL Server日志以查看发生了什么。我很确定这个电话不会奇迹般地无所事事。 – TomTom
@DynamicVariable问题已更新 – Ali