Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a result set is empty?

I have a sql statement that returns no hits. For example, 'select * from TAB where 1 = 2'.

I want to check how many rows are returned,

cursor.execute(query_sql)  rs = cursor.fetchall() 

Here I get already exception: "(0, 'No result set')"

How can I prevend this exception, check whether the result set is empty?

like image 473
Tao Venzke Avatar asked May 15 '13 09:05

Tao Venzke


People also ask

How do you do null check for ResultSet in Java?

The wasNull() method of the ResultSet interface determines whether the last column read had a Null value. i.e. whenever you read the contents of a column of the ResultSet using the getter methods (getInt(), getString etc...) you can determine whether it (column) contains null values, using the wasNull() method.

What is RS next () in Java?

The next() method of the ResultSet interface moves the pointer of the current (ResultSet) object to the next row, from the current position. Statement stmt = con. createStatement(); ResultSet rs = stmt. executeQuery("Select * from MyPlayers"); rs. next();

How can we view a ResultSet?

The ResultSet interface declares getter methods (for example, getBoolean and getLong ) for retrieving column values from the current row. You can retrieve values using either the index number of the column or the alias or name of the column. The column index is usually more efficient. Columns are numbered from 1.

Can ResultSet be null?

No matter how many rows are returned(starting from 0), the resultSet will never be null. The only case in which a resultset will remain null is when an exception is thrown... but the program flow will jump to the Exception handling block anyways.


1 Answers

cursor.rowcount will usually be set to 0.

If, however, you are running a statement that would never return a result set (such as INSERT without RETURNING, or SELECT ... INTO), then you do not need to call .fetchall(); there won't be a result set for such statements. Calling .execute() is enough to run the statement.


Note that database adapters are also allowed to set the rowcount to -1 if the database adapter can't determine the exact affected count. See the PEP 249 Cursor.rowcount specification:

The attribute is -1 in case no .execute*() has been performed on the cursor or the rowcount of the last operation is cannot be determined by the interface.

The sqlite3 library is prone to doing this. In all such cases, if you must know the affected rowcount up front, execute a COUNT() select in the same transaction first.

like image 101
Martijn Pieters Avatar answered Sep 21 '22 18:09

Martijn Pieters