2013-05-17 47 views
0

此:無法連接到本地SQL數據庫

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

返回此錯誤:

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)

什麼想法?

+0

檢查http://blog.sqlauthority.com/2009/05/21/sql-server-fix-error-provider-named-pipes-provider-error-40-could-not-open-a-connection- to-sql-server-microsoft-sql-server-error /和http://www.mssqltips.com/sqlservertip/2340/resolving-could-not-open-a-connection-to-sql-server-errors/ –

+1

在這裏看看在創建連接字符串到SQL Server數據庫時需要的所有幫助。http://www.connectionstrings.com/sql-server-2008 – MethodMan

+0

@JoeBabcock你可以在字符串前面放@ @ a- la @「yourpathhere」使它成爲一個字符串文字,並且您不再需要雙反斜線,這使得它更容易......不要忘記添加它們,如果你明白我的意思 –

回答

0

(從error occurred while establishing a connection to SQL Server複製)

的問題涉及到應用程序的.NET版本4.0

沒有運行按照以下頁面: http://www.connectionstrings.com/sql-server-2012#sqlconnection

你需要.NET 4.0及以上使用命名管道:

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 

的信息提供了命名管道那麼這可以在連接字符串中使用:

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

你缺少數據源上的雙反斜線。它正在讀取\v作爲垂直標籤。

或者你可以在整個字符串之前使用前導@作爲逐字串(如果你這樣做,那麼你需要清除你的文件路徑上額外的反斜槓)。