Consider a hypothetical case where I have to retrieve some details from the database based on the userId and the sample code is given below
private String getpassword(String username) {
PreparedStatement statement = null;
ResultSet resultSet = null;
Connection conn = null;
final String selectQuery = "SELECT password FROM " + "users WHERE username=?";
try {
conn = dataSource.getConnection();
statement = conn.prepareStatement(selectQuery);
statement.setString(1, username);
resultSet = statement.executeQuery();
if (resultSet.next()) {
}
} catch (SQLException e) {
// log it
}
//return
}
This username is actually coming from the client side and the user can tamper the data (if he wants to). So will preparedStatements prevent from accepting quotes and send only the filtered form of SQL to the database.
For eg: I can provide username= ' or 1=1 and it will be a valid SQL statement. But if the driver escapes the quotes from user inputs, then they would prevent sql injections.
What is the general understanding of the same ?