Reputation: 29
When I use server explorer in Visual Studio and add a local DB on my D drive, I get a connection string and the connection test is successful.
But when I want to use that connection string like below to attach the database without the wizard and jut by code, I get an error on opening the connection, my connection string is provided below:
string coonection_string ="Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\\x\book.mdf;Integrated Security=True;Connect Timeout=30";
try
{
SqlConnection myconnection = new SqlConnection(coonection_string);
myconnection.Open();
MessageBox.Show(" connected");
}
catch (Exception e1)
{
MessageBox.Show(e1.ToString());
}
Upvotes: 1
Views: 550
Reputation: 3192
Keep an @ symbol in-front of the connection string,in C# backslash is a escape character
string coonection_string =@"Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\\x\book.mdf;Integrated Security=True;Connect Timeout=30";
else your connection string may not be in correct format
SqlConnectionStringBuilder.AttachDBFilename Property
Upvotes: 1
Reputation: 1
Try to put @ before connection string. We use @ before strings to avoid having to escape special characters.
string coonection_string =@"Data Source=(LocalDB) \v11.0;AttachDbFilename=D:\\x\book.mdf;Integrated Security=True;Connect Timeout=30";
Upvotes: 1
Reputation: 5808
Your connection string is wrong. Eigher mdf file in your local project or sqlexpres or you can use a database name in the connection string like
Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|MyDatabase.mdf;Integrated Security=True;User Instance=True
or
Data Source=(LocalDb)\v11.0;Initial Catalog=MyDatabase;Integrated Security=SSPI;
Check this link.
DB Connection string in Web.config to use attached .mdf database won't work
Always use Web.config file for connection string and access the entry in code as
Dim mWebSvr As String = ConfigurationSettings.AppSettings("Connectionstring")
Upvotes: 1