您的位置:宽带测速网 > 网络知识 > c# sqlhelper如何进行参数化查询

c# sqlhelper如何进行参数化查询

2025-06-16 19:21来源:互联网 [ ]

在C#中,使用SqlHelper类进行参数化查询可以有效地防止SQL注入攻击。以下是一个简单的示例,展示了如何使用SqlHelper类进行参数化查询:

首先,确保已经安装了SqlHelper库。如果没有安装,可以通过NuGet包管理器安装:

Install-Package SqlHelper

然后,创建一个SqlHelper实例:

using System;using System.Data;using System.Data.SqlClient;using SqlHelper;public class SqlHelperInstance{private static string connectionString = "your_connection_string";public static DataTable ExecuteSqlQuery(string sql, SqlParameter[] parameters){using (SqlConnection connection = new SqlConnection(connectionString)){connection.Open();using (SqlCommand command = new SqlCommand(sql, connection)){command.Parameters.AddRange(parameters);using (SqlDataReader reader = command.ExecuteReader()){DataTable result = new DataTable();result.Load(reader);return result;}}}}}

现在,你可以使用SqlHelperInstance类执行参数化查询。以下是一个示例:

using System;using System.Data;using System.Data.SqlClient;using SqlHelper;class Program{static void Main(string[] args){string sql = "SELECT * FROM Users WHERE UserId = @UserId AND UserName = @UserName";SqlParameter[] parameters = new SqlParameter[]{new SqlParameter("@UserId", SqlDbType.Int) { Value = 1 },new SqlParameter("@UserName", SqlDbType.NVarChar) { Value = "John Doe" }};DataTable result = SqlHelperInstance.ExecuteSqlQuery(sql, parameters);Console.WriteLine("User ID: " + result.Rows[0]["UserId"]);Console.WriteLine("User Name: " + result.Rows[0]["UserName"]);}}

在这个示例中,我们定义了一个参数化查询,用于从Users表中获取指定用户的信息。我们使用SqlParameter数组来传递参数,并将它们添加到SqlCommand对象中。最后,我们执行查询并处理结果。

c#