问题描述
如何在C#中将数组与SQL查询进行比较?
DataTable dt = context.getData("Select * from emp_detail where EState = any(" +data+ ")",CommandType.Text);
解决方法
您可以将数据数组序列化为格式正确的字符串,然后将select命令更改为类似的内容:
Select * from emp_detail where EState in ('a','b',...)
此解决方案仅适用于具有少量项目的阵列。
,我认为您可以这样做以获取要比较的字符串列表:
using System.Linq;
namespace ExampleNamespase
{
public class SimpleClass
{
private class TypeExample
{
public string Property { get; }
}
private void CompareData(TypeExample[] exampleArray)
{
var items = string.Join(",",exampleArray.Select(t => t.Property));
var sql = $"Select * from emp_detail where EState in ({items}) ";
}
}
}
或者,如果您使用的是简单的字符串列表:
private void CompareData(string[] exampleArray)
{
var items = string.Join(",exampleArray);
var sql = $"Select * from emp_detail where EState in ({items}) ";
}
要防止注入,请使用Dapper库:
using System.Data;
using Dapper;
namespace ExampleNamespase
{
public class SimpleClass
{
private void CompareData(string[] exampleArray,IDbConnection connection)
{
var sql = "Select * from emp_detail where EState in @items ";
var result = connection.Query<YourTypeClass>(sql,new { items = exampleArray });
}
}
}
说明: 第一个示例使用Linq库使用Select方法检索对象的属性,并使用string.Join方法将结果列表连接为以逗号分隔的字符串。
第二个示例演示了相同的方法,只是使用字符串数组和相同的字符串。Join方法用于联接。
在第三个示例中,使用Dapper库执行请求,我认为应该首选此方法,因为它有助于避免SQL注入,并且还简化了数据库的工作。要执行查询,我们可以传递一个对象列表以与数据库中的值进行比较,Dapper将能够自行处理它。我们只需要在请求中使用@符号定义变量,然后将对象传递给处理对象,该对象将具有相同的名称。
P.S。我为我的英语道歉))
更新:
尝试一下:
private void CampareData(string[] exampleArray,IDbConnection connection)
{
var clearItems = exampleArray.Select(s => $"'{s}'").ToArray();
var sql = "Select * from emp_detail where EState in @items ";
var result = connection.Query<YourTypeClass>(sql,new { items = clearItems });
}
在此变体中,我们将每个项目都用sql括在引号中,并且查询中应包含以下内容:... in('item1','item2'...)