You're attempting to create a validation class for your Java program by connecting to a MySQL database and retrieving specific rows based on a constructor parameter. However, your code is not functioning as intended.
To resolve this issue, you need to modify your code to utilize the setString() method to set the userID parameter. This not only ensures that the statement is formatted correctly but also prevents SQL injection, which is important for database security.
Here's the updated code snippet:
import java.sql.*; import java.sql.PreparedStatement; import java.sql.Connection; public class Validation { private PreparedStatement statement; private Connection con; private String x, y; public Validation(String userID) { try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/test", "root", ""); statement = con.prepareStatement( "SELECT * from employee WHERE userID = ?"); statement.setString(1, userID); ResultSet rs = statement.executeQuery(); while (rs.next()) { x = rs.getString(1); System.out.print(x); System.out.print(" "); y = rs.getString(2); System.out.println(y); } } catch (Exception ex) { System.out.println(ex); } } }
By incorporating these changes, you'll be able to effectively pass parameters to your JDBC PreparedStatement, mitigating SQL injection risks and ensuring the correct retrieval of data from your database.
The above is the detailed content of How to Safely Pass Parameters to a JDBC PreparedStatement in Java?. For more information, please follow other related articles on the PHP Chinese website!