ResultSet#isFirst()不表示存在一行

时间:2018-12-08 07:50:14

标签: java ms-access select jdbc ucanaccess

我只是在从java程序中的ms访问中获取数据时遇到一个问题,我正在使用ucanaccess驱动程序,以下是我的代码

public void loginUser(){
  // variables
    Connection connection = null;
    Statement statement = null;
    ResultSet resultSet = null;

    // Step 1: Loading or 
    // registering Oracle JDBC driver class
    try {

        Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
    }
    catch(ClassNotFoundException cnfex) {

        System.out.println("Problem in loading or "
                + "registering MS Access JDBC driver");
        cnfex.printStackTrace();
    }

    // Step 2: Opening database connection
    try {

        String msAccDB; 
                msAccDB = "C:/Users/Hidayat Ullah/Documents/Record.accdb";
        String dbURL = "jdbc:ucanaccess://"
                + msAccDB; 

        // Step 2.A: Create and 
        // get connection using DriverManager class
        connection = DriverManager.getConnection(dbURL); 

        // Step 2.B: Creating JDBC Statement 
  String  sql= "SELECT * FROM Student WHERE studentid = ? AND password = ?";
 PreparedStatement pstmt = connection.prepareStatement(sql);
  //printing here loginId.getText() and loginPass.getText() always has value 
  //i entered in the gui
 pstmt.setString(1, loginId.getText()); 
 pstmt.setString(2,loginPass.getText());
 ResultSet row = pstmt.executeQuery();

if(row.isFirst()){
  JOptionPane.showMessageDialog(null, "Student ID 
:"+row.getString("studentid"));
 System.exit(0);
  }else{
   JOptionPane.showMessageDialog(null, "No such record exists in database 
 against this ID, either ID or Password is incorrect.");
 System.exit(0);
 }

问题是当我输入数据库中的用户ID和密码时,它始终不返回任何记录。我在这里做什么错了?

1 个答案:

答案 0 :(得分:1)

最初创建ResultSet对象时,将其放置在第一行之前 ,因此.isFirst()将返回false,直到您调用.next()ResultSet 放在第一行上(如果存在)。您的代码不必调用.isFirst(),而只需调用.next(),如果它返回true,则至少找到一个匹配的行。