0

Sometimes I have to query database while reading from a ResultSet. Is there a way to check, for a given Statement instance, if it is occupied with a ResultSet or not?

EDIT:

After reading @MarkRotteveel comment, I change my question from Connection to Statement.

He suggests that this is not possible and not a good practice either. So should I create a Statement for every query? And why I can't do this check on a Statement?

Minh Nghĩa
  • 854
  • 1
  • 11
  • 28
  • From the manual "A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set. " https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html.. Also `stmt.executeQuery(query)` throws a SQLException want there is a error meaning `while (resultSet.next()) {` would never be executed. – Raymond Nijland Aug 21 '18 at 15:16
  • 1
    So you want to know if there is an existing ResultSet object associated with a given Connection object. Is that correct? – Gord Thompson Aug 21 '18 at 15:25
  • @GordThompson Yes! – Minh Nghĩa Aug 21 '18 at 15:29
  • @RaymondNijland Could you elaborate your idea? – Minh Nghĩa Aug 21 '18 at 15:31
  • 2
    There is nothing like that in JDBC itself. Technically a JDBC driver should support allowing multiple open result sets on the same connection (assuming auto-commit is disabled and you're using multiple statements). Why do you want this? And if you write your code correctly your code would already 'know' this. If your code doesn't 'know' this, it suggests you are not managing your resources well enough. – Mark Rotteveel Aug 21 '18 at 15:34
  • @MarkRotteveel So, can I do this with a `Statement`? I just want to separate `Connection` and `Statement` handling from my code. – Minh Nghĩa Aug 21 '18 at 15:49
  • Yes, create as many statements as you need. – The Impaler Aug 21 '18 at 16:15
  • I admit to you all I am too lazy to do that :)))))) So this is the only way. – Minh Nghĩa Aug 21 '18 at 16:17
  • 2
    I repeat, there is nothing in JDBC to check this, not on a connection nor on a statement. You should structure your code in such a way this is already clear. I still fail to see **why** you need to know this. Please illustrate your question with code where this is relevant. – Mark Rotteveel Aug 21 '18 at 17:14

0 Answers0