在 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,但實際上是連接協定配置問題。預設連接字串使用 server=local 或 server=(local),會導致 ADO.NET 嘗試使用 Named Pipes 協定連接,但在某些環境下(特別是 SQL Server 2000)Named Pipes 未啟用或權限不足,導致連線失敗。
修改 web.config 中的連接字串,將 server=local 改為 本機電腦名稱 或 127.0.0.1,強制使用 TCP/IP 協定:
<connectionStrings>
<add name="MyConn"
connectionString="server=YOUR_MACHINE_NAME;database=YourDB;integrated security=sspi;"
providerName="System.Data.SqlClient" />
</connectionStrings>
或明確指定 TCP/IP:
server=tcp:127.0.0.1,1433;database=YourDB;integrated security=sspi;
Data Source 而非 server 關鍵字,語意更清晰。