gpt4 book ai didi

java - 为什么我会收到此 SQLServerException : "The result set has no current row"

转载 作者:行者123 更新时间:2023-12-01 22:14:07 26 4
gpt4 key购买 nike

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

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 循环应该阻止程序尝试访问数据。

最佳答案

if 语句后面有一个分号,充当空语句:

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

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

关于java - 为什么我会收到此 SQLServerException : "The result set has no current row",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31415854/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com