我正在尝试为我的程序制作验证类。我已经建立了与MySQL数据库的连接,并且已经在表中插入了行。该表由firstName,lastName和userID领域。现在,我想通过构造函数的参数在数据库中选择特定的行。
firstName
lastName
userID
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 = " + "''" + 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); } } }
但这似乎没有用。
您应该使用setString()方法设置userID。这既可以确保语句的格式正确,又可以防止SQL injection:
setString()
SQL injection
statement =con.prepareStatement("SELECT * from employee WHERE userID = ?"); statement.setString(1, userID);
Java教程中有一个很好的教程,说明如何PreparedStatement正确使用。
PreparedStatement