简体   繁体   中英

Can't Connect to Local SQL Database

This:

SqlConnection myConnection = new SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename='C:\\Users\\Joe\\Documents\\Visual Studio 2012\\Projects\\FileIO\\FileIO\\Database.mdf';Integrated Security=True");
try
{
   myConnection.Open();
}
catch (Exception e)
{
   Console.WriteLine(e.ToString());
}

Returns this error:

A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll System.Data.SqlClient.SqlException: 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)

Any Ideas?

You're missing the double backslash on the data source. It's reading the \\v as a vertical tab.

Or you can use a leading @ before the whole string to treat it as a verbatim string (if you do this then you'll need to clear out the extra backslashes on your filepath).

(Copied from error occurred while establishing a connection to SQL Server )

The problem was related to the application not running in .net version 4.0

According to the following page: http://www.connectionstrings.com/sql-server-2012#sqlconnection

You need .net 4.0 and up to use named pipes:

The Server=(localdb) syntax is not supported by .NET framework versions before 4.0.2. However the named pipes connection will work to connect pre 4.0.2 applications to LocalDB instances.

SqlLocalDB.exe create MyInstance
SqlLocalDB.exe start MyInstance
SqlLocalDB.exe info MyInstance

The info provides the named pipe then this can be used in the connection string:

<add name="conn" 
providerName="System.Data.SqlClient" 
connectionString="Server=np:\\.\pipe\LOCALDB#B1704E69\tsql\query"/>

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