在运行时创建具有多个参数值的“字符串”sql 查询的最佳方法?

问题描述 投票:0回答:1

我需要创建一个 SQL 查询,还需要将其作为 REST API 中的请求正文传递。我正在努力寻找将此 sql 创建为字符串的最佳方法

到目前为止我所拥有的是通过 StringBuilder

        stringBuilder.append("SELECT * FROM employee "
                             + "WHERE employeeId = 'A' and employeeName IN "
                             + "('ABC', 'PQR', 'ZYZ')"
                             + " and active = 'ACTIVE' and DEPARTMENTID in ('")
                     .append(params.getDepartmentIdList)
                     .append("'")
                     .append(" and deactivate = false")
                     .append(" and triggerId = '")
                     .append(params.gettriggerId())
                     .append("'");

        return stringBuilder.toString();

我得到的输出正是我想要的,除了departmentId,departmentIdList 填充为

('[ABC, BWP, DAS, DAD]' instead of 'ABC', 'BWP', 'DAS', 'DAD'

注意 DEPARTMENTID 值中是 []

SELECT * FROM employee WHERE employeeId = 'A' and employeeName IN ('ABC', 'PQR', 'ZYZ') and active = 'ACTIVE' and DEPARTMENTID in ('[ABC, BWP, DAS, DAD]' and deactivate = false and triggerId = '123456'

any suggesstions or any other way I could achieve this ?

java sql
1个回答
0
投票

为了可读性,我会分开查询并提前准备数据。

var query = """
SELECT * FROM employee 
WHERE employeeId = %s and employeeName IN '%s'
AND active = %s and DEPARTMENTID in '%s'
AND deactivate = %s
AND triggerId = %s
""";
var employeeNames = String.join(",", List.of('ABC', 'PQR', 'ZYZ'));  
var departmentIds = String.join(",", params.getDepartmentIdList());
var queryBody = String.format(query, employeeId, 
                                     employeeNames, 
                                     'ACTIVE', 
                                     depeartmentIds, 
                                     'false', 
                                     params.gettriggerId());
© www.soinside.com 2019 - 2024. All rights reserved.