Junior — Middle
How is parameter passing performed in SQL queries?
sobes.tech AI
Answer from AI
Passing parameters in SQL queries is usually done using prepared statements. This helps prevent SQL injection and improves performance when executing similar queries repeatedly.
In Java, this is done through the PreparedStatement class. Instead of directly inserting values into the query string, placeholders ? are used, which are then replaced with specific values using the setXXX methods.
Example:
String sql = "SELECT * FROM users WHERE id = ? AND status = ?";
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setInt(1, 10); // first parameter
pstmt.setString(2, "active"); // second parameter
ResultSet rs = pstmt.executeQuery();
This approach ensures security and ease of working with parameters.