使用PreparedStatement登录在Java中不起作用[重复]

问题描述 投票:0回答:1
public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter username: ");
    String un = sc.nextLine();
    System.out.print("Enter password: ");
    String up = sc.next();
    sc.close();
    try
    {
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDB",
    "root", "pass");
    String q = "select * from users where username = ? and password = ?";       
    PreparedStatement ps = con.prepareStatement(q);
    ps.setString(1, un);
    ps.setString(2, up);
    ResultSet rs = ps.executeQuery(q);
    if(rs.next())
        System.out.println("Welcome "+un);
    else
        System.out.println("Invalid username or password");
    }
    catch(Exception e)
    { System.out.println(e.getMessage()); }

}

输出为:

Enter username: Raja
Enter password: 111
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? and password = ?' at line 1

为什么?应该可以,但是显示错误

java database jdbc console prepared-statement
1个回答
4
投票
ResultSet rs = ps.executeQuery(q);

您必须使用无参数版本,否则,您将尝试执行字符串的内容,而不是已准备好的语句。

ResultSet rs = ps.executeQuery();
© www.soinside.com 2019 - 2024. All rights reserved.