Sobes.tech
Junior — Middle

What methods of protection against SQL injection are applicable when using JDBC in Java?

sobes.tech AI

Answer from AI

Main methods of protection against SQL injection when using JDBC:

  • Using PreparedStatement instead of Statement. In PreparedStatement, parameters are passed separately, which prevents malicious SQL code injection.
  • Validation and escaping of input data, although this is less reliable than PreparedStatement.

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 guarantees that the entered data will not be interpreted as part of the SQL query.