为什么我得到这个SQLServerException:“结果集没有当前行”

时间:2015-07-14 19:41:22

标签: java sql-server jdbc

我正在尝试使用以下代码访问数据库:

try {   
        //Create Data Source and set properties
        SQLServerDataSource ds = new SQLServerDataSource();
        ds.setServerName(MY_SERVER);
        ds.setDatabaseName(MY_DATABASE);
        ds.setIntegratedSecurity(true);

        //Establish connection
        Connection conn = ds.getConnection();

        //Define query
        String query = "SELECT * from dbo.InvPrice;";

        //Create Statement and execute query
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(query);

        //Print off table column names to make sure 
        //that we have actually connected to table
        ResultSetMetaData rsmd = rs.getMetaData();
        int numberOfColumns = rsmd.getColumnCount();
        for(int i=1; i<=numberOfColumns; i++)
            System.out.print(rsmd.getColumnName(i)+" ");

        System.out.println();

        //Check to make sure ResultSet isn't empty
        if(!rs.isBeforeFirst())
            System.out.println("NO DATA");

        //loop through ResultSet, printing off first column
        while(rs.next()); {
            System.out.println(rs.getString(1));
        } 
    }
    catch (Exception e) {
     e.printStackTrace();
    }
    finally {
        try { if (rs != null) rs.close(); } catch (Exception e) {};
        try { if (stmt != null) stmt.close(); } catch (Exception e) {};
        try { if (conn != null) conn.close(); } catch (Exception e) {};
    }

}

当我运行代码时,会打印出正确的列名,但是当我尝试使用rs.getString(1)访问ResultSet中的数据时,会抛出com.microsoft.sqlserver.jdbc.SQLServerException。它指定“结果集没有当前行”,但我看不出这是怎么可能的,因为如果光标超过数据的末尾,while循环应该阻止程序尝试访问数据。 / p>

1 个答案:

答案 0 :(得分:3)

if语句作为空语句后有一个分号:

while(rs.next()); {  // remove the semi-colon

这会导致ResultSet的光标遍历所有行,直到没有人指向它,从而导致异常。