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