[英]How can I get rid of a trailing AND in Java
这是一个愚蠢的问题,但是如何在Java中的sql语句中删除结尾的AND?
我根据给定的Profile对象动态生成语句。 因此,如果对象具有“名称= person1”和“地址=示例路”,则该语句应为:
select * from Profile where name = 'person1' and address = 'example road'
问题是我正在使用for循环遍历对象的声明字段,因此在末尾添加了额外的AND:
select * from Profile where name = 'person1' and address = 'example road' and
摆脱尾随AND的最佳方法是什么?
有些人会简单地从结果字符串的末尾修整最后的“和”,但是通常最好避免写最后的和第一位。
如果循环看起来像这样:
for (String sqlCondition : sqlConditionsList) {
sqlStatement.append(sqlCondition).append(" and ");
}
然后,我建议将其更改为以下内容:
boolean separatorNeeded = false;
for (String sqlCondition : sqlConditionsList) {
if (separatorNeede) {
sqlStatement.append(" and ");
}
sqlStatement.append(sqlCondition);
separatorNeeded = true;
}
仅在实际需要时,才在要迭代的列表的连续项目之间添加“和”分隔符。
您应该使用准备好的语句。 像这样构建查询使您容易受到SQL注入和其他攻击的影响。
如果您必须继续使用当前的方法,那么一个快速的解决方法是通过正则表达式删除最终的AND
:
String sql = "select * from Profile where name = 'person1' and address = 'example road' and";
sql = sql.replaceAll("(?i)\\s+and$", "");
您应该使用准备好的语句或ORM。 但是,如果您仍然想以这种容易出错的方式进行操作,则可以这样做:
public static void main(String args[]) {
String[] params = new String[3];
params[0] = "x = y";
params[1] = "z = a";
params[2] = "b = d";
String result = String.join(" and ", params);
System.out.println(result);
}
使用join方法比弄乱尾随和是更好的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.