Consider a hypothetical case where I need to get some data from a database based on userId, and an example 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) {
}
}
This username actually happens on the client side, and the user can change the data (if he wants). In this way, prepared states prevent quotation marks and send only the filtered SQL form to the database.
For example, I can specify username = 'or 1 = 1, and this will be a valid SQL statement. But if the driver escapes quotes from user inputs, then they will prevent sql injections.
What is the general understanding of the same?
source
share