请告诉为什么控制不会进入pst.setString(1,userName);和下一行控制直接进入elseif(more = true)第3行

时间:2015-06-07 03:51:43

标签: java

在准备好的语句转到else if(more){}

后查看控件
try{
    //System.out.println("iam in first line");
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection(url,user,passsword);
    String userName = ex.getUserName();
    String password = ex.getPassword();
    PreparedStatement pst = con.prepareStatement("Select * from employee where username = ? and password = ? "); `after this line control is not there`
    pst.setString(1, userName);
    pst.setString(2, password);
    int k = pst.executeUpdate();
    boolean  more;
    if(k > 0)
    {
        //boolean  more = rs.next();
        more = true;
    }
    else {
        more = false;
    }
    if(!more)
    {
        System.out.println("you are not a registered user!");
        ex.setValid(false);
    }
    else if(more)
    {
        String firstName = rs.getString("name");
        String lastName = rs.getString("rollnumber");

        System.out.println("Welcome " + firstName); `control coming here`
        ex.setFirstName(firstName);
        ex.setLastName(lastName);
        ex.setValid(true);
    }

}
catch(Exception tex)
{
    tex.printStackTrace();
    //System.out.println("hey there is an exception " +ex);
}

1 个答案:

答案 0 :(得分:1)

主要问题是使用int k = pst.executeUpdate();

您的查询不是更新语句,因此执行更新没有意义,这可能会一直返回0,因为没有更新的行。

而是使用executeQuery,它返回ResultSet,可用于确定是否有与您的查询匹配的行,例如

try{
    //System.out.println("iam in first line");
    Class.forName("com.mysql.jdbc.Driver");
    try (Connection con = DriverManager.getConnection(url,user,passsword)) {
        String userName = ex.getUserName();
        String password = ex.getPassword();
        PreparedStatement pst = con.prepareStatement("Select * from employee where username = ? and password = ? "); `after this line control is not there`
        pst.setString(1, userName);
        pst.setString(2, password);
        try (ResultSet rs = pst.executeQuery()) {
            if (rs.hasNext()) {
                // Registered
            } else {
                // Unregistered
            }
        }
    }
}
catch(Exception tex)
{
    tex.printStackTrace();
    //System.out.println("hey there is an exception " +ex);
}

您可能需要仔细查看JDBC(TM) Database Access trail