指数2超出范围

时间:2013-07-25 14:44:24

标签: java jdbc

PreparedStatement preparedStatement = Connectionstring().prepareStatement(
            "Select Username from dbo.LoginDetails where Username = ? and Password =?");
  String User = tf_Fname.getText();
  String _Pass = new String(tf_Lname.getPassword());
        preparedStatement.setString(1, User);
        preparedStatement.setString(2, _Pass);
        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()) 
        {
            System.out.println("Username is "+ resultSet.getString(1)+"Password is "+resultSet.getString(2));  
        }

没有

+"Password is "+resultSet.getString(2)

它工作正常,它是从数据库打印用户名 但是,这也会引发错误。

com.microsoft.sqlserver.jdbc.SQLServerException: The index 2 is out of range.

3 个答案:

答案 0 :(得分:8)

Select Username from .....................

select子句中只有一列。

将其更改为

  Select Username, yourpasswordcolumnname from......

答案 1 :(得分:7)

您只从表中检索一列:

"Select Username from dbo.LoginDetails where Username = ? and Password =?");

试试这个:

 "Select Username, Password from dbo.LoginDetails where Username = ? and Password =?");

然后你的代码应该工作,在另一个相关的注释,永远不要存储密码为"明文",总是使用单向加密方法,并使用盐!

相关:You're Probably Storing Passwords Incorrectly

答案 2 :(得分:2)

select * from dbo.LoginDetails where Username = ? and Password =?

将为您提供所需的信息,以便您选择dbo.LoginDetails中的所有列,而不只是选择一列,Username,就像您现在一样