Passing parameters to a JDBC PreparedStatement
Solution 1:
You should use the setString()
method to set the userID
. This both ensures that the statement is formatted properly, and prevents SQL injection
:
statement =con.prepareStatement("SELECT * from employee WHERE userID = ?");
statement.setString(1, userID);
There is a nice tutorial on how to use PreparedStatement
s properly in the Java Tutorials.
Solution 2:
There is a problem in your query..
statement =con.prepareStatement("SELECT * from employee WHERE userID = "+"''"+userID);
ResultSet rs = statement.executeQuery();
You are using Prepare Statement.. So you need to set your parameter using statement.setInt()
or statement.setString()
depending upon what is the type of your userId
Replace it with: -
statement =con.prepareStatement("SELECT * from employee WHERE userID = :userId");
statement.setString(userId, userID);
ResultSet rs = statement.executeQuery();
Or, you can use ?
in place of named value - :userId
..
statement =con.prepareStatement("SELECT * from employee WHERE userID = ?");
statement.setString(1, userID);
Solution 3:
If you are using prepared statement, you should use it like this:
"SELECT * from employee WHERE userID = ?"
Then use:
statement.setString(1, userID);
?
will be replaced in your query with the user ID passed into setString
method.
Take a look here how to use PreparedStatement.
Solution 4:
Do something like this, which also prevents SQL injection attacks
statement = con.prepareStatement("SELECT * from employee WHERE userID = ?");
statement.setString(1, userID);
ResultSet rs = statement.executeQuery();