I wrote the following part which is a Java method with two STRING arguments login and pass, representing a user’s login name and password, to check whether the user is found in a database table.
Statement stmt = connection.createStatement();
ResultSet rs = statement.executeQuery ("SELECT * FROM users WHERE username = '"
+ login + "' AND passwd = '" + pass + "'");
The code when tested worked correctly. I read in a book that there are situations where it could potentially generate an SQL error but it does not mention exactly the circumstances under which the above code could result in an SQL error. Could you please briefly expain me these situations? And also how can I write a version of the code that would prevent the possibilityof such an error occuring?
The first problem is that this piece of code is vulenrable to
SQL Injection. To avid that you can usePrepared Statements. This might be one potential threat the book might be talking about.http://www.unixwiz.net/techtips/sql-injection.html
example for using prepared statement