我正在尝试为我的程序制作验证课程。我已经建立了与MySQL数据库的连接,我已经在表中插入了行。该表由 firstName , lastName 和 userID 字段组成。现在我想通过构造函数的参数在数据库中选择一个特定的行。
import java.sql。*; import java.sql.PreparedStatement; import java.sql.Connection; 公共类验证{ 私人PreparedStatement声明; 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); } } }但似乎没有你应该使用
docs / api / java / sql / PreparedStatement.html#setString%28int,%20java.lang.String%29rel =noreferrer> setString() 设置 userID 的方法。这既可以确保语句格式正确,又可以防止 SQL注入: statement = con.prepareStatement(SELECT * from employee WHERE userID =?); statement.setString(1,userID);关于如何使用 PreparedStatement 在 Java教程中正确使用。
I'm trying to make my validation class for my program. I already establish the connection to the MySQL database and I already inserted rows into the table. The table consists of firstName, lastName and userID fields. Now i want to select a specific row on the database through my parameter of my constructor.
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); } } }but it doesn't seem work.
解决方案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 PreparedStatements properly in the Java Tutorials.
更多推荐
将参数传递给JDBC PreparedStatement
发布评论