Junior — Middle
How can a database be protected from SQL injections?
sobes.tech AI
Answer from AI
To protect a database from SQL injection in Java, prepared statements (PreparedStatement) are commonly used. They allow separating SQL code from data, preventing malicious SQL commands from being injected.
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();
Other protection methods:
- Validation and filtering of input data.
- Using ORM frameworks that automatically generate safe queries.
- Minimizing database access rights.
But the main and most effective way is to use prepared statements.