How to find whether a ResultSet is empty or not in Java? [duplicate]
How can I find that the ResultSet
, that I have got by querying a database, is empty or not?
Immediately after your execute statement you can have an if statement. For example
ResultSet rs = statement.execute();
if (!rs.next()){
//ResultSet is empty
}
Definitely this gives good solution,
ResultSet rs = stmt.execute("SQL QUERY");
// With the above statement you will not have a null ResultSet 'rs'.
// In case, if any exception occurs then next line of code won't execute.
// So, no problem if I won't check rs as null.
if (rs.next()) {
do {
// Logic to retrieve the data from the resultset.
// eg: rs.getString("abc");
} while(rs.next());
} else {
// No data
}
Do this using rs.next()
:
while (rs.next())
{
...
}
If the result set is empty, the code inside the loop won't execute.
If you use rs.next() you will move the cursor, than you should to move first() why don't check using first() directly?
public void fetchData(ResultSet res, JTable table) throws SQLException{
ResultSetMetaData metaData = res.getMetaData();
int fieldsCount = metaData.getColumnCount();
for (int i = 1; i <= fieldsCount; i++)
((DefaultTableModel) table.getModel()).addColumn(metaData.getColumnLabel(i));
if (!res.first())
JOptionPane.showMessageDialog(rootPane, "no data!");
else
do {
Vector<Object> v = new Vector<Object>();
for (int i = 1; i <= fieldsCount; i++)
v.addElement(res.getObject(i));
((DefaultTableModel) table.getModel()).addRow(v);
} while (res.next());
res.close();
}
if (rs == null || !rs.first()) { //empty } else { //not empty }
Note that after this method call, if the resultset is not empty, it is at the beginning.
Calculates the size of the java.sql.ResultSet:
int size = 0;
if (rs != null) {
rs.beforeFirst();
rs.last();
size = rs.getRow();
}
(Source)
精彩评论