C# 组合字符串并在特定位置用另一个字符串将其分隔
我有九个字符串,它们要么是SQL查询,要么只是空的(“”),这取决于几个复选框的状态。我需要将它们组合成另一个字符串,如C# 组合字符串并在特定位置用另一个字符串将其分隔,c#,sql,string,logical-operators,C#,Sql,String,Logical Operators,我有九个字符串,它们要么是SQL查询,要么只是空的(“”),这取决于几个复选框的状态。我需要将它们组合成另一个字符串,如 string OP = "AND"; string query = "select * from table where " + string1 + OP + string2 + OP + string3 + OP + ... + " order by ID;" 问题是,在两个字符串之间,我需要一个和或一个或。但是,如果任何字符串为空,它将给我一个SQL错误。SQL不理解以
string OP = "AND";
string query = "select * from table where " + string1 + OP + string2 + OP + string3 + OP + ... + " order by ID;"
问题是,在两个字符串之间,我需要一个和
或一个或
。但是,如果任何字符串为空,它将给我一个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;
字符串查询=
“从表中选择*,其中”
+string1
+String.IsNullOrEmpty(string2)?“”:(OP+string2)
+String.IsNullOrEmpty(string3)?“”:(OP+string3)
+ ...
+“按ID订购;”
空值测试
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;"
您可以将字符串放入数组中,删除空字符串,然后使用
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()) +
不要使用原始SQL。至少,使用。否则,您很容易受到SQL注入和混乱的、容易出错的命令串联代码的攻击。您的代码是什么样子的?让我们从这一点开始,从你所得到的开始工作。你知道,你可能应该提供括号,因为你可以是混合运算符。此外,您应该在这里使用stringbuilders。另外,不要这样做:这是不安全的(除非你完全控制所有的值)。即便如此:使用参数查询(也称为准备好的语句)是的。但是说真的,别这样。使用prepared语句Seems是更好的解决方案,但会给我带来一个错误“无法将类型'System.Collections.Generic.IEnumerable'隐式转换为字符串[]”。但另一个也可以正常工作。谢谢:)@daydr3amer:哦,你使用的是一个旧的框架。然后需要在
Where()
之后添加.ToArray()
。Join
的重载不会在您的版本中获取可枚举项。
String.Join(op, conditions.Where(c => c.Length > 0).ToArray()) +