在与 SQL Server 建立连接时出现与网络相关的或特定于实例的错误。未找到或无法访问服务器。请验证实例名称是否正确并且 SQL Server 已配置为允许远程连接。 (provider: SQL Network Interfaces, error: 26 - 定位指定的服务器/实例时出错)
static void Main(string[] args)
{
SqlConnection dataConnection = new SqlConnection();
// try
// {
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = ".\SQLExpress";
builder.InitialCatalog = "Northwind";
builder.IntegratedSecurity = true;
dataConnection.ConnectionString = builder.ConnectionString;
dataConnection.Open();
Console.Write("Please enter a customer ID (5 characters):");
string customerId = Console.ReadLine();
SqlCommand dataCommand = new SqlCommand();
dataCommand.Connection = dataConnection;
dataCommand.CommandType = CommandType.Text;
dataCommand.CommandText =
"SELECT OrderID,OrderDate,ShippedDate,ShipName,ShipAddress," +
"ShipCity,ShipCountry" +
"FROM Orders WHERE CustomerID=@CustomerIdParam";
SqlParameter param = new SqlParameter("@CustomerxidParam", SqlDbType.Char, 5);
param.Value = customerId;
dataCommand.Parameters.Add(param);
Console.WriteLine("About to gind orders for customer {0}\n\n", customerId);
SqlDataReader dataReader = dataCommand.ExecuteReader();
while (dataReader.Read())
{
int orderId = dataReader.GetInt32(0);
DateTime orderDate = dataReader.GetDateTime(1);
DateTime shipDate = dataReader.GetDateTime(2);
string shipName = dataReader.GetString(3);
string shipAdddress = dataReader.GetString(4);
string shipCity = dataReader.GetString(5);
string shipCountry = dataReader.GetString(6);
Console.WriteLine(
"Order:{0}\nPlaced:{1}\nShipped: {2}\n" +
"To Address: {3}\n{4}\n{5}\n{6}\n\n", orderId, orderDate,
shipDate, shipName, shipAdddress, shipCity, shipCountry
);
dataReader.Close();
}
// }
//catch (SqlException e)
//{
// Console.WriteLine("Error accessing the database:{0}", e.Message);
//}
//finally
//{
// dataConnection.Close();
//}
}
}
}
首先先确定电脑上安装了SQL Server(SQLEXPRESS)服务,并正常启动。
然后,进入Microsoft SQL Server 2005->配置工具->SQL Server外围应用配置器
选择“服务和连接的外围应用配置器”
选择“MSSSQLSERVER->Database Engine->远程连接",计算机默认的是仅限本地连接,所以选择”本地连接和远程连接->同时使用TCP/IP和named pipes(B)"
设置好后,单击应用和确定,并返回“服务”
停止服务后重新启动。
设置好以上服务后,接下来再看看SQL Server Configuration Manager里面的设置。
进入Microsoft SQL Server 2005->配置工具->SQL Server Configuration Manager
选择SQL Server 2005 网络配置->MSSSQLSERVER的协议,把协议VTA禁用,默认是启动的。
以上配置好后,到最后一步了。重启SQL Server