1

I have to query a MS SQL DB using java. I am querying DB using following code

         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());

When I query DB manually using query string, I am able to successfully gets results but res.getRow() shows 0.

3 Answers 3

1

you forgot to include next() to fetch the first record:

ResultSet res=stmt.executeQuery(querystr);
if(res.next()) // add this line
    System.out.print(res.getRow());
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

Thanks. yes, I forget to add res.next
0

The getRow() method gives the row number of current row. The first row is number 1, the second number 2, and so on.

and gives the current row number as 0 if there is no current row which is your case.

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

2 Comments

@juergend yeah he tried the query manually on MS SQL. But in no way he can use getRow() in SQL String. The query is fine and data is fetched but because of using getRow() wongly in java he got unexpected result.
getrow was just used to find rowcount. Query returns no result. I am getting exception "No current row in the ResultSet" when try to access resultset

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.