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);
}
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:\ )
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)