【问题标题】:Combine strings and separate them by another string at specific locations组合字符串并在特定位置用另一个字符串分隔它们
【发布时间】:2012-09-15 16:32:16
【问题描述】:

我有九个字符串,它们要么是 SQL 查询,要么是空的 (""),具体取决于几个复选框的状态。我需要将它们组合在另一个字符串中,例如

string OP = "AND";
string query = "select * from table where " + string1 + OP + string2 + OP + string3 + OP + ... + " order by ID;"

问题是,在字符串之间,我需要一个ANDOR。但如果任何字符串为空,它会给我一个 SQL 错误。 SQL 不理解类似

的内容
select * from table where AND a = "adsf" AND AND AND z = "fghj" AND order by ID;

它必须看起来像这样:

select * from table where a = "adsf" AND z = "fghj" order by ID;

【问题讨论】:

  • 不要使用原始 SQL。 至少使用 parameterized queries。否则你很容易受到 SQL 注入和混乱、容易出错的命令连接代码的攻击。
  • 你的代码是什么样的?让我们从你所拥有的开始工作。
  • 您知道,您可能应该提供括号,因为您可能会混合运算符。此外,您应该在这里使用 stringbuilders。另外,不要这样做:这是不安全的(除非您绝对控制所有值)。即使这样:使用参数查询(a.k.a Prepared Statements)

标签: c# sql string logical-operators


【解决方案1】:

您可以将字符串放入数组中,删除空字符串,然后使用Join 组合它们:

string[] conditions = new string[] {
  string1,
  string2,
  string3,
  string4
};

string op = " and ";
string query =
  "select * from table where " +
  String.Join(op, conditions.Where(c => c.Length > 0)) +
  "select * from table where ";

对于框架 3.5 更改为:

  String.Join(op, conditions.Where(c => c.Length > 0).ToArray()) +

【讨论】:

  • 似乎是更好的解决方案,但给我一个错误“无法将类型 'System.Collections.Generic.IEnumerable' 隐式转换为字符串 []。”但另一个也可以正常工作。谢谢你:)
  • @daydr3amer:哦,您使用的是较旧的框架。然后你需要在Where()之后添加.ToArray()Join 没有在您的版本中采用可枚举的重载。
【解决方案2】:
字符串查询 = “从表中选择 *” + 字符串 1 + String.IsNullOrEmpty(string2) ? " " : (OP + string2) + String.IsNullOrEmpty(string3) ? " " : (OP + string3) + ... + " 按 ID 排序;"

【讨论】:

  • 是的。但。说真的,别这样。使用准备好的语句
【解决方案3】:

空值测试

string query = "select * from table where " + 
String.IsNullOrEmpty(string1) ? "" : (string1+OP) + 
String.IsNullOrEmpty(string2) ? "" : (string2+OP) + 
...+
String.IsNullOrEmpty(string9) ? "" : string9;


//in case your string ends with AND which will if `string9` is empty
if (query.EndsWith("AND"))
{
    int andIndex = query.LastIndexOf("AND");
    query = query.Substring(0, andIndex);
}

query = query + " order by ID;"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多