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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3