Java防止SQL注入的方式有以下几种:
示例代码:
String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, username);
statement.setString(2, password);
ResultSet resultSet = statement.executeQuery();
示例代码:
String sql = "{CALL authenticateUser(?, ?)}";
CallableStatement statement = connection.prepareCall(sql);
statement.setString(1, username);
statement.setString(2, password);
ResultSet resultSet = statement.executeQuery();
示例代码:
String username = request.getParameter("username");
String password = request.getParameter("password");
// 验证和过滤输入数据
if (username.matches("[a-zA-Z0-9]+")) {
// 执行SQL查询
String sql = "SELECT * FROM users WHERE username = '" + username + "' AND password = '" + password + "'";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
}
总体来说,最好的方式是使用参数化查询,因为它能够最大程度地防止SQL注入攻击。而其他方式则是在某些场景下的替代方案。