我正在使用PreparedStatement进行DELETE查询。
我的ps配置为此
config.sql.statement.delete=DELETE FROM ? WHERE ?
然后在我的Java代码中,我设置了这样的值
ps.setString(1, schemaName == "F" ? "FUNDS" : "MANDATE" + "." + tableName);
ps.setString(2, whereClause);
whereClause设置如下
String whereClause = " ";
for (int m = 0; m < columns.size(); m++) {
String columnData = jsonObj.getString(columns.get(m));
log.info("Column Data for column " + columns.get(m) + " Value: " + columnData);
if (m == 0) {
whereClause = whereClause + columns.get(m) + " = " + "'" + columnData + "'";
} else {
whereClause = whereClause + " AND " + columns.get(m) + " = " + "'" + columnData + "'";
}
}
log.info("WHERE CLAUSE: " + whereClause);
whereClause被记录为:
WHERE CLAUSE: CLIENT_END_DT = '9998-12-31' AND CLIENT_START_DT = '2017-04-06' AND FUND_CODE = 'TEST_CODE'
我得到的错误:
com.microsoft.sqlserver.jdbc.SQLServerException: An expression of non-boolean type specified in a context where a condition is expected, near '@P1'.
google之后,我注意到它可能与我如何配置WHERE子句有关。我使用这个ps的方式有任何确切的问题吗?
答案 0 :(得分:0)
使用PreparedStatement,您不能使用数据库对象名称,即table,columns作为参数。
在sql查询中,为表和列使用特定名称,以避免SQL注入。
DELETE FROM table_name WHERE column1 = ? and column2 = ?
也许,您可以使用自定义占位符来解决相同的问题,小心SQL攻击!
config.sql.statement.delete=DELETE FROM $table WHERE $whereClause
稍后将您的sql构建为:
String sql = ...; /* your logic */
sql = sql.replace("$table",(schemaName == "F" ? "FUNDS" : "MANDATE" + "." + tableName));
sql = sql.replace("$whereClause",whereClause);
ps=conn.prepareStatement(sql);