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");
// 驗(yàn)證和過濾輸入數(shù)據(jù)
if (username.matches("[a-zA-Z0-9]+")) {
// 執(zhí)行SQL查詢
String sql = "SELECT * FROM users WHERE username = '" + username + "' AND password = '" + password + "'";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
}
總體來說,最好的方式是使用參數(shù)化查詢,因?yàn)樗軌蜃畲蟪潭鹊胤乐筍QL注入攻擊。而其他方式則是在某些場(chǎng)景下的替代方案。