简体   繁体   中英

Connecting to database using code - C#

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());
}

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")

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

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";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM