Question

Based on what I learned here, I'm using this connection string:

using (var conn = new SqlConnection(@"AttachDBFilename=C:\HoldingTank\AdventureWorksLT2012_Database\AdventureWorksLT2012_Data.MDF;Integrated Security=True;User Instance=true"))

...to (attempt to) attach to a local SQL Server db, but I get this exception at runtime:

System.Data.SqlClient.SqlException was unhandled by user code
  HResult=-2146232060
  Message=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)
  Source=.Net SqlClient Data Provider

Based on my legacy MS Access connection string, I had previously also had:

Provider=System.Data.SqlClient;

prior to the "AttachDBFilename=..." part of the connection string, but that caused an exception of its own...

Was it helpful?

Solution

You are missing a few values in the connection string. Here is one I used recently:

"Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\mydbname.mdf;Initial Catalog=mydbname;Integrated Security=True"

I'm thinking the most likely culprit is the lack of the "Initial Catalog" value.

OTHER TIPS

The connection string you need will depend on several factors, such as the edition of SQL Server (LocalDB/Express/Standard), whether or not it's a named instance, and the type of authentication (SQL vs Integrated) you have in place.

The answer from @zippit is a good example of a connection string for LocalDB using integrated security.

The same string to a Sql Express server would look like this:

"Data Source=serverNameOrIpAddress\sqlepxress;AttachDbFilename=|DataDirectory|\mydbname.mdf;Initial Catalog=mydbname;Integrated Security=True"

..and to a standard edition of Sql Server would look like this:

"Data Source=serverNameOrIpAddress\sqlepxress;AttachDbFilename=|DataDirectory|\mydbname.mdf;Initial Catalog=mydbname;Integrated Security=True"

..and to a named instance on a standard edition of Sql Server would look like this:

"Data Source=serverNameOrIpAddress\instanceName;AttachDbFilename=|DataDirectory|\mydbname.mdf;Initial Catalog=mydbname;Integrated Security=True"

All those assume integrated authentication. If you have sql authentication set up, you would substitute "Integrated Security=True" with "User Id=username; Password=pword;"

Also, if the sql server is on the same machine, you can use this for the Data Source parameter for Sql Express

.\sqlexpress

..and this for standard Sql Server

(local)

Here's a site I've found useful: Connection Strings

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top