【问题标题】:Error in Java code :Parameter index out of range (1 > number of parameters, which is 0)Java代码中的错误:参数索引超出范围(1>参数数量,即0)
【发布时间】:2019-04-04 12:58:26
【问题描述】:

如果数据库中存在该行,我正在尝试验证用户名和密码。但是我让参数索引超出范围(1 > 参数数量,即 0)。请帮忙

Scanner in = new Scanner(System.in);
String password = in .next();
String username = in .next();

PreparedStatement ps = 
                connect.prepareStatement
               ( "select  LastName,BirthDate from employees where LastName= '" + username + "'  and BirthDate = '" + password + "'"  );


            ps.setString (1, username);
            ps.setString (2, password);
            ResultSet rs = ps.executeQuery();

            if (rs.next()) {

                 System.out.println("login completed");
            } else {
                // Quest not completed yet
                 System.out.println("login failed");

                }

【问题讨论】:

  • PreparedStatement 查询语法不是这样工作的。请参阅 API。
  • 单独传递参数的要点是您不要将它们直接粘贴到 SQL 中。
  • 试试这个:select LastName,BirthDate from employees where LastName=? and BirthDate=?.

标签: java jdbc


【解决方案1】:

您将字符串连接与设置准备好的语句参数混合在一起。您应该只使用两者之一,最好是后者。您的代码应如下所示:

PreparedStatement ps = connect.prepareStatement ( 
    "select LastName,BirthDate from employees where LastName=? and BirthDate=?"
);
ps.setString (1, username);
ps.setString (2, password);
ResultSet rs = ps.executeQuery();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-29
    • 1970-01-01
    • 1970-01-01
    • 2016-01-19
    • 2014-03-29
    • 1970-01-01
    • 1970-01-01
    • 2017-05-21
    相关资源
    最近更新 更多