一、簡介
在很多要求性能的項目中,我們都要使用傳統的ADO.NET的方式來完成我們日常的工作;目前有一些網友問有關于.NET Core操作SQL Server的問題在本文中解答一下。
本文旨在指出,在.NET Core中使用ADO.NET SqlClient操作SQL SERVER數據庫時的一些常見的問題,在本文的第三部分,如果只關心解決問題,請?zhí)^第兩部分進行閱讀。
二、使用ADO.NET
首先建立好一個ASP.NET MVC Core Project 或 .NET Core Class Library Project , 當然也可以是一個控制臺程序;
要使用ADO.NET和SQLCLient就要引用System.Data.Common和System.Data.SqlClient兩個程序集,點這兩個名稱可以跳到它們的Nuget地址。
在.NET CORE的ADO.NET中功能被程序集所劃分,其實System.Data.Common封裝的就是ADO.NET的抽象部分,它包含如下命名空間和類型:
System.Data.Common.DbConnection
System.Data.Common.DbException
System.Data.Common.DbParameter
System.Data.DbType
System.Data.Common.DbDataReader
System.Data.Common.DbCommand
System.Data.Common.DbTransaction
System.Data.Common.DbParameterCollection
System.Data.Common.DbProviderFactory
可以使用兩種方法進行安裝:
1.NuGet
PM> Install-Package System.Data.Common
PM> Install-Package System.Data.SqlClient
2.Project.json
"dependencies": {
"System.Data.Common": "4.1.0-*",
"System.Data.SqlClient" : "4.1.0-*",
"System.Runtime": "4.1.0-*"
}
3.使用SqlClient
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環(huán)境用會依賴于VC++的運行時,目前依賴的為: Microsoft Visual C++ 2012 Runtime