在 Windows XP + .NET Framework 2.0 + SQL Server 2000 環境下,ASP.NET 應用連接數據庫時常遇到如下錯誤:
An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (Provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
雖然錯誤提示提到 SQL Server 2005,但實際環境是 SQL Server 2000。核心原因在於 web.config 中的連接字符串配置不當:使用 server=local 或 server=(local) 時,Named Pipes 協議在某些網絡配置下無法正確解析本地實例名。
將連接字符串中的 server=local 改為本地計算機名稱(或 IP 地址 127.0.0.1)。例如:
<connectionStrings>
<add name="MyConn"
connectionString="Data Source=MYCOMPUTERNAME;Initial Catalog=MyDB;Integrated Security=SSPI;"
providerName="System.Data.SqlClient" />
</connectionStrings>
也可顯式指定 TCP/IP 協議:
Data Source=tcp:MYCOMPUTERNAME,1433;Initial Catalog=MyDB;Integrated Security=SSPI;
User ID 與 Password。aspnet_regiis -pef)。通過修正連接字符串中的服務器標識,即可快速解決此類連接失敗問題。