当我在Visual Studio中遇到这个错误时,
"在建立与SQL Server的连接时,发生了与网络相关或特定于实例的错误。未找到服务器或无法访问服务器。验证实例名称是否正确,SQL Server是否配置为允许远程连接。(提供商:命名管道提供商,错误:40 -无法打开到SQL Server的连接)"
...它是在执行下面的c#代码期间,它试图获取我的SQL Server数据以在网格中显示。中断恰好发生在表示connect.Open()的行上:
using (var connect = Connections.mySqlConnection)
{
const string query = "SELECT Name, Birthdate, Narrative FROM Friends";
using (var command = new SqlCommand(query, connect))
{
connect.Open();
using (var dr = command.ExecuteReader())
{
while (dr.Read())
{
// blah
}
}
}
}
It was inexplicable because the SQL query was very simple, I had the right connection string, and the database server was available. I decided to run the actual SQL query manually myself in SQL Management Studio and it ran just fine and yielded several records. But one thing stood out in the query results: there was some improperly encoded HTML text inside a varchar(max) type field within the Friends table (specifically, some encoded comment symbols of the sort <!-- lodged within the "Narrative" column's data). The suspect data row looked like this:
Name Birthdate Narrative
==== ========= ==============
Fred 21-Oct-79 <!--HTML Comment -->Once upon a time...
注意编码的HTML符号“<”,它代表一个“<”字符。不知何故,它进入了数据库,而我的c#代码无法接收它!它每次都失败在connect.Open()行!在我手动编辑数据库表Friends中的一行数据并输入解码后的“<”字符之后,一切都正常了!这一行应该是这样的:
Name Birthdate Narrative
==== ========= ==============
Fred 21-Oct-79 <!--HTML Comment -->Once upon a time...
我使用下面这个简单的UPDATE语句编辑了一个不好的行。但如果你有几行违规的HTML编码,你可能需要一个更详细的UPDATE语句,使用REPLACE函数:
UPDATE Friends SET Narrative = '<!--HTML Comment -->Once upon a time...' WHERE Narrative LIKE '<%'
因此,这个故事的寓意是(至少在我的情况下),在将HTML内容存储到数据库之前清理它,这样您就不会在第一时间得到这个神秘的SQL Server错误!(如果你需要更多信息,正确地消毒/解码你的HTML内容是另一个值得单独在StackOverflow搜索的讨论主题!)