我的代码中有一个漏洞,我正在尝试修复它。
为此,在 SQL 查询中,我使用PreparedStatements 安全地注入(inject)参数,如下所示:
String runQuery(String value) {
String myReturn;
String query = "select VALUE from " + tableName + " where config = ?";
try(PreparedStatement ps = con.prepareStatement(query)){
ps.setString(1, value);
try(ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
myReturn = rs.getString(1);
} else {
throw new BusinessException("noSQLResultSet");
}
}
} catch (Exception sqlException) {
throw new BusinessException("SQLException");
}
return myReturn;
}
我的问题是关于表tableName
的名称,我目前正在从服务器上的属性文件中检索它,但是从我使用PreparedStatements看到的情况来看,我无法注入(inject)表的名称因为这是不允许的。如何以安全的方式指定表名而不连接查询中的值?
最佳答案
没有特别简单的方法;一种解决方案是将输入列入白名单:如果它仅包含字母和下划线,那么就可以了。
请注意,您的异常处理非常糟糕,您正在丢弃所有有用的信息!试试throw new BusinessException("uncaught", e);
- 如果 BusinessException 是您的代码,请确保添加该构造函数(您可以只调用 super(msg, cause);
)。
关于java - 带有表名的PreparedStatement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66190624/