1

我必须使用 java 查询 MS SQL DB。我正在使用以下代码查询数据库

         Class.forName("net.sourceforge.jtds.jdbc.Driver");
         Connection conn = DriverManager.getConnection(
                 "jdbc:jtds:sqlserver://XXX.XX.XX>XX:1433/DBNAME", "USERNAME", "Password");

         querystr="select DATEDIFF(second,Finish_Time,ReqTime) As FinishDifference from DB.SCHEMA.TABLE where ID='123'";
         Statement stmt=conn.createStatement();
         ResultSet res=stmt.executeQuery(querystr);
         System.out.print(res.getRow());

当我使用查询字符串手动查询数据库时,我能够成功获得结果,但 res.getRow() 显示 0。

4

3 回答 3

1

您忘记包含next()以获取第一条记录:

ResultSet res=stmt.executeQuery(querystr);
if(res.next()) // add this line
    System.out.print(res.getRow());
于 2012-06-27T10:40:59.113 回答
0

Initially ResultSet returns current cursor position.

ResultSet res=stmt.executeQuery(querystr);
res.getRow();// It will return 0 (Zero) because result set is pointing to begining of the first record

res object is pointing to 0th position of table in your DB. When you iterate with the help of res.next();

It will move to next record and now if you call

 res.getRow();// It will return 1 because cursor is moved to 1st record of table.

Try this.

while(res.next())
{
         System.out.println(res.getRow());
}

It will print the All rows number one by one.

于 2012-06-27T11:23:43.160 回答
0

getRow()方法给出当前行的行号。第一行是数字 1,第二行是数字 2,依此类推。

如果您的情况没有当前行,则将当前行号设为 0。

http://docs.oracle.com/javase/1.4.2/docs/api/java/sql/ResultSet.html#getRow ()

于 2012-06-27T10:44:52.517 回答