【问题标题】:Adding a list of strings to OracleCommand.Parameters in C# [duplicate]在 C# 中将字符串列表添加到 OracleCommand.Parameters [重复]
【发布时间】:2013-02-10 14:39:54
【问题描述】:

以下查询有一个要分配字符串列表的参数:

select * from a_table where something in :list_of_strings

我有一个 C# List<string>,我想将它分配给 list_of_strings 参数。

给定一个OracleCommand(代表上述查询),我如何将我的List<string> 绑定到命令的list_of_strings 参数?

【问题讨论】:

标签: c# oracle ado.net


【解决方案1】:

实际上,您不能将单个参数绑定到值列表。在这种情况下,您可以将值连接到查询字符串。
但是,这是不建议的,因为您可以在 IN 子句中设置的值是有限的。

List<string> list = new List<string>();
list.Add("1");
list.Add("2");
list.Add("3");
list.Add("4");

string listStr = string.Join(",", list);
//result: "1,2,3,4"

如果你的字符串列表是一个字符串列表,你可以这样做:

List<string> list = new List<string>();
list.Add("one");
list.Add("two");
list.Add("three");
list.Add("four");

string listStr = string.Concat("'", string.Join("','", list), "'");
//result: "'one','two','three','four'"

查询字符串:

string query = string.Format("select * from a_table where something in({0})", listStr);

Obs:您可能必须处理列表为空的可能性。

另一种可能性是在临时表中插入所有值并在 select 语句中使用它。与连接技术相比,这将具有无限字符串值的优势并避免在 DBMS 上进行新的硬解析:

SELECT * 
    FROM A_TABLE 
   WHERE SOMETHING IN(SELECT SOMETHING FROM TEMP_TABLE)

【讨论】:

  • 小心点。如果你没有清理你的列表参数,你就会面临 SQL 注入。
猜你喜欢
  • 1970-01-01
  • 2020-09-14
  • 2015-12-10
  • 2018-12-13
  • 1970-01-01
  • 2012-08-28
  • 1970-01-01
  • 2014-09-30
  • 2020-01-18
相关资源
最近更新 更多