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 ?
The only sure way to prevent SQL Injection attacks is input validation and parametrized queries including prepared statements. The application code should never use the input directly. The developer must sanitize all input, not only web form inputs such as login forms.
Prepared statements offer two major benefits: The query only needs to be parsed (or prepared) once, but can be executed multiple times with the same or different parameters. When the query is prepared, the database will analyze, compile and optimize its plan for executing the query.
A prepared statement “sanitizes” the input. This means it makes sure that whatever the user enters is treated as a string literal in SQL and NOT as a part of the SQL query. It may also escape certain characters and detect/remove malicious code.
Prepared statements are resilient against SQL injection, because parameter values, which are transmitted later using a different protocol, need not be correctly escaped. If the original statement template is not derived from external input, SQL injection cannot occur.
According to this, yes: http://en.wikipedia.org/wiki/SQL_injection
In that case the statement is already compiled and injected code would not be interpreted (and thus not be executed) again.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With