Passing Parameters to a JDBC PreparedStatement
Creating a validation class for a Java program often involves querying a database. The following code attempts to select a specific row from a table using a PreparedStatement with a parameter:
public class Validation { // ... public Validation(String userID) { try { // ... statement = con.prepareStatement( "SELECT * from employee WHERE userID = " + "''" + userID); // ... } catch (Exception ex) { // ... } } // ... }
However, this code may not work because the SQL statement is not formatted correctly.
Solution:
To correctly pass a parameter to a PreparedStatement, use the setString() method:
statement = con.prepareStatement("SELECT * from employee WHERE userID = ?"); statement.setString(1, userID);
This method sets the value of the first parameter (?) to the specified user ID. It ensures that the statement is formatted properly and prevents SQL injection, a security vulnerability that occurs when malicious SQL code is injected into a query.
For more information on using PreparedStatements, refer to the Java Tutorials.
The above is the detailed content of How to Safely Pass Parameters to a JDBC PreparedStatement?. For more information, please follow other related articles on the PHP Chinese website!