编辑:我了解较新的 .NET 项目从
System.Data.SqlClient
到 Microsoft.Data.SqlClient
的迁移。我无法理解的是 *.Data.SqlClient
命名空间如何与 SQL Server 通信。考虑到 Microsoft 现在已弃用其客户端之一 SQL Native Client (SNAC),我想到了这个问题。
即
*.Data.SqlClient
命名空间如何与 SQL Server 2022 数据库通信?随着 SQL Native Client 弃用的宣布,开发人员是否需要担心他们的代码库?
使用 C# 编码并使用 Microsoft SQL Server 后端,我们目前正在将数据库从 SQL Server 2019 迁移到较新的 SQL Server 2022 环境。我们的代码库明确使用
SqlConnection
或更新的 System.Data.SqlClient
命名空间中的 Microsoft.Data.SqlClient
对象。
根据 Microsoft 网站,SQL Server Native Client (SNAC) 现已在 SQL Server 2022 中弃用。我们的代码库是否需要迁移以不再使用 System.Data.SqlClient.SqlConnection
对象(或
Microsoft.Data.SqlClient.SqlConnection
)才能继续与较新的 SQL Server 2022(+) 实例一起运行?连接字符串示例:
<add name="myConnection"
connectionString="Server=DEV-SQLSERVER2019-01.mycompany.local,1433;TrustServerCertificate=True;Database=Tokens;User ID=TokensApp;Password=ABC123"
providerName="Microsoft.Data.SqlClient"/>
示例代码:
//using System.Data.SqlClient;
using Microsoft.Data.SqlClient;
private static string CreateToken(string code, string email)
{
string token;
try
{
using (SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnection"].ConnectionString))
{
sqlConn.Open();
using (SqlCommand sqlCmd = new SqlCommand())
{
sqlCmd.Connection = sqlConn;
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = "spCreateToken";
sqlCmd.Parameters.Add("@Token", SqlDbType.UniqueIdentifier).Value = NEW_GLOBAL_TOKEN();
sqlCmd.Parameters.Add("@Code", SqlDbType.NVarChar, 6).Value = code.ToUpper();
sqlCmd.Parameters.Add("@Email", SqlDbType.NVarChar, 80).Value = email.ToLower();
token = sqlCmd.ExecuteScalar().ToString();
}
}
}
catch (SqlException exSQL) when (exSQL.Message.Contains("Violation of UNIQUE KEY constraint"))
{
throw new Exception(String.Format("This email address '{0}' has already been sent an invitiation.", email));
}
catch (Exception ex) when (ex.Message.Equals("Object reference not set to an instance of an object."))
{
throw new InvalidOperationException(String.Format("The email address provided '{0}' has already signed-up.", email));
}
return token;
}
如果确实需要更改此代码库 - 我应该如何在我的 C# 代码库中连接 Microsoft SQL Server 2022+ 数据库:
SqlConnection
类来连接到我们的 Microsoft SQL Server 数据库的代码库。如果需要的话,看起来迁移路径对于使用新的 SQL 客户端对象类型来确保正确的功能会很麻烦。
绝对与 C# 中的 SqlClient 无关。它是一个 ODBC 驱动程序,供 C/C++ 和其他利用 ODBC 的工具使用。
这只是粉笔和奶酪、苹果和橙子,不合逻辑的逻辑。它与谈话完全、完全、完全、绝对无关,与谈话无关,它在另一个世界。在 C# 中,忘记您听说过 Native Client,它不适合您。您需要担心的是
Microsoft.Data.SqlClient
或更旧但仍受支持的
System.Data.SqlClient
。