如何在 Java 中查找 ResultSet 是否为空?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2331716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find whether a ResultSet is empty or not in Java?
提问by Yatendra Goel
How can I find that the ResultSet
, that I have got by querying a database, is empty or not?
我怎样才能发现ResultSet
我通过查询数据库得到的 是空的?
采纳答案by Paul
Immediately after your execute statement you can have an if statement. For example
在执行语句之后,您可以立即使用 if 语句。例如
ResultSet rs = statement.execute();
if (!rs.next()){
//ResultSet is empty
}
回答by Dolph
回答by Scott Smith
Do this using rs.next()
:
使用rs.next()
以下方法执行此操作:
while (rs.next())
{
...
}
If the result set is empty, the code inside the loop won't execute.
如果结果集为空,循环内的代码将不会执行。
回答by Kachwahed
If you use rs.next() you will move the cursor, than you should to move first() why don't check using first() directly?
如果你使用 rs.next() 你会移动光标,而不是你应该移动 first() 为什么不直接使用 first() 检查?
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();
}
回答by Santosh Tiwari
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.
注意,这个方法调用之后,如果结果集不为空,就是在开头。
回答by purush
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
}