using System;
using System.Data.SqlClient;
namespace DBTest
{
public class Program
{
public static void Main(string[] args)
{
using (SqlConnection con = new SqlConnection(ConnStr)) {
con.Open();
try {
using (SqlCommand command = new SqlCommand("SELECT * FROM SAMPLETABLE", con)) {
command.ExecuteNonQuery();
}
}
catch {
Console.WriteLine("Something went wrong");
}
}
Console.Read();
}
}
} 三、常见问题
1.SQL Server版本问题
这个问题,表象上体现的是一个连接超时的错误:
Unhandled Exception: System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 35 - An internal exception was caught) ---> System.AggregateException: One or more errors occurred. (No such device or address) ---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException: No such device or address
但是这个错误却是因为SQL Server的版本问题造成的,.NET Core中的SqlClient能支持的SQL Server最小版本为 SQL Server 2008 R2 SP3,如果你的数据库小于这个版本,就会出现这个异常。
官方的Issues在此:https://github.com/dotnet/corefx/issues/9719 SQL Server 2008 R2 SP3补丁的下载地址如下:
https://www.microsoft.com/zh-cn/download/details.aspx?id=44271
还有就是将连接字符串中的加入Mul‌tipleActiveResultSet‌s=false
2.Runtime运行时问题
在部署到Windows和IIS时,System.Data.SqlClient 这个程序集在Windows环境用会依赖于VC++的运行时,目前依赖的为: Microsoft Visual C++ 2012 Runtime