Example of SQL injection
The following Java servlet code, used to perform a login function, illustrates the vulnerability by accepting user input without performing adequate input validation or escaping meta-characters:
String sql = "select * from user where username='" + username +"' and password='" + password + "'";
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
if (rs.next()) {
loggedIn = true;
out.println("Successfully logged in");
} else {
out.println("Username and/or password not recognized");
}
================
Now please tell me how can we modify this code , so that it is free from SQL Injection
You need to use the
PreparedStatementclass and add parameters.See the documentation.