Junior — Middle
What methods can be used to protect a database from SQL injections?
sobes.tech AI
Answer from AI
Protecting a database from SQL injections is an important aspect of security. Main protection methods in Java:
- Using Prepared Statements — query parameters are passed separately, which eliminates the possibility of malicious SQL code injection.
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();
-
Validation and filtering of input data — checking the format and content of data before using it in queries.
-
Using ORM frameworks (e.g., Hibernate) — they automatically generate safe queries.
-
Minimizing access rights — database accounts should have the minimum necessary permissions.
-
Regular updates and patches — keeping the database software and drivers up to date.
These methods collectively significantly reduce the risk of successful SQL injection.