Reputation: 32321
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
Upvotes: 1
Views: 690
Reputation: 107
If you are providing the values at runtime to the particular sql query you should use preparedStatement,
along with you should better to use form tag (in the view page for eg: index.html,login.jsp etc.,) method as POST instead of GET to overcome the SQL injection
Upvotes: 0
Reputation: 9326
Use a prepared statement instead of building your own query string : http://download.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html
Upvotes: 2
Reputation: 887365
You need to use the PreparedStatement
class and add parameters.
See the documentation.
Upvotes: 5
Reputation: 210402
You do this by cleaning up username
and password
so that they don't contain dangerous characters, either by escaping them or by removing them.
This might explain the problem better.
Upvotes: 2