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注入攻擊。而其他方式則是在某些場景下的替代方案。