我正在尝试动态构建SQL字符串,例如:
"SELECT * FROM TABLE WHERE A = B AND C = D AND E = F AND"
最后,如何在没有额外 AND 的情况下更好地构建此 SQL 查询?
我的代码:
let where = "";
if (_conditions.length > 0) {
where = "WHERE ";
for (let i = 0; i < _conditions.length; i++) {
let curr_cond = _conditions[i];
let keys = Object.keys(curr_cond);
where += keys[0] + " = '" + curr_cond[keys[0]] + "' AND ";
}}
我假设您正在使用循环构建 WHERE 子句。
使用某种字符串连接会更优雅。
在大多数语言中,有一种方法可以使用"分隔符"将一堆字符串值连接在一起。
例如在Java中:
List<String> conditions = List.of("A = B","C = D","E = F");
String whereClause = String.join(" AND ",conditions);
或者在 Python 中:
conditions = ['A = B', 'C = D', 'E = F']
whereclause = ' AND '.join(conditions)
或者在Javascript中:
var _conditions = ["A = B", "C = D", "E = F"];
var whereClause = _conditions.join(" AND ");
您可能甚至不需要检查列表的长度;空列表或一个项目的列表不会包含分隔符。