Junior — Middle
What methods can be used to prevent vulnerabilities related to SQL code injection through parameters in JDBC?
sobes.tech AI
Answer from AI
To prevent vulnerabilities related to SQL code injection through parameters in JDBC, the following methods are used:
-
PreparedStatement — using parameterized queries, where parameters are passed separately and not inserted directly into the SQL string. This prevents interpretation of parameters as code.
-
Validation and escaping of input data — checking and sanitizing data before using it in queries.
-
Using ORM — for example, Hibernate, which automatically constructs safe queries.
Example of using PreparedStatement:
String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setString(1, username);
pstmt.setString(2, password);
ResultSet rs = pstmt.executeQuery();
This approach eliminates the possibility of malicious SQL code injection through parameters.