2 回答
TA贡献1842条经验 获得超21个赞
简单(而且不安全!)的方法是这样的:
// package declaration
// imports
public class Main {
public static void main(String[] args) {
if (args.length >= 1) {
String query = "select FOO from BLAH a where a.BAZ = '"
+ args[0] + "'";
Connection connection = ...
Statement statement = connection.createStatement();
ResultSet rs = statement.execute(query);
// etcetera
} else {
// report missing command line argument.
}
}
}
问题是通过字符串连接组装 SQL 查询容易受到SQL 注入攻击。特别是当某些“参数”可能来自不可信的来源时。
因此,更好(更安全)的方法是使用PreparedStatement, 及其语法安全的参数替换机制:
// package declaration
// imports
public class Main {
public static void main(String[] args) {
if (args.length >= 1) {
String query = "select FOO from BLAH a where a.BAZ = ?";
Connection connection = ...
PreparedStatement statement = connection.createPreparedStatement(query);
statement.setString(1, args[0]);
ResultSet rs = statement.execute();
// etcetera
} else {
// report missing command line argument.
}
}
}
添加回答
举报