我有一个列表对象,我发送到SQL查询
UPDATE <table name> SET status= 'CLOSED' WHERE dlno IN ("+StringUtils.join(deals, ',')+") ";
我的交易对象如下
1549886508071HELMPFN
如何在此处传递字符串
[SQL0103] Numeric constant 1549886508071HELMPFN not valid.
答案 0 :(得分:1)
字符串常量需要用单引号括起来。在你的情况下,这将是:
UPDATE <table name>
SET status = 'CLOSED'
WHERE dlno IN ('"+StringUtils.join(deals, "', '") +"') ";
答案 1 :(得分:1)
使用绑定变量将解决您的引用问题,并使您的代码安全地防止SQL注入:
List<String> deals = ImmutableList.of("abc", "123", "def");
StringBuilder questionMarks = new StringBuilder("?");
for (int i=1;i<deals.size();i++) {
questionMarks.append(",?");
}
Connection conn = ...; // presumably, you already have this
PreparedStatement stmt = conn.prepareStatement(
"UPDATE my_table SET status= 'CLOSED' WHERE dlno IN (" + questionMarks + ")");
for (int i=1;i<=deals.size();i++) { // note these are 1-indexed, not 0-indexed
stmt.setString(i, deals.get(i-1));
}
stmt.executeUpdate();
基本上,您将生成一个显示UPDATE my_table SET status = 'CLOSED' WHERE dlno IN (?,?)
的查询(与参数数量对应的问号数),然后您将使用stmt.setString
更新它们。然后您可以执行更新。
另请注意,您需要处理SQLException
并关闭声明。为清楚起见,删除了这里。