Java 如何检查结果集是否为空
我编写了下面的代码来检索表中的所有记录,但在创建新表时,我想检查ResultSet是否为空,如果为空,则不显示消息 我该怎么做 代码:Java 如何检查结果集是否为空,java,sqlite,jdbc,Java,Sqlite,Jdbc,我编写了下面的代码来检索表中的所有记录,但在创建新表时,我想检查ResultSet是否为空,如果为空,则不显示消息 我该怎么做 代码: public void selectAll() throws SQLException, ClassNotFoundException { if (this.isTableExists(this.TABLE_NAME)) { Connection conn = this.getConnection(); Statement stmt = co
public void selectAll() throws SQLException, ClassNotFoundException {
if (this.isTableExists(this.TABLE_NAME)) {
Connection conn = this.getConnection();
Statement stmt = conn.createStatement();
ResultSet resSet = stmt.executeQuery("select * from "+this.TABLE_NAME+";");//i want to check if it is empty or not.
while (resSet.next()) {
Log.d(TAG, "selectAll", "ID: "+resSet.getString(ID_COL));
Log.d(TAG, "selectAll", "Node: "+resSet.getString(NODE_ID_COL));
Log.d(TAG, "selectAll", "Lat: "+resSet.getString(LAT_COL));
Log.d(TAG, "selectAll", "Lng: "+resSet.getString(LNG_COL));
Log.d(TAG, "selectAll", "xmlPath: "+resSet.getString(XML_PATH_COL));
}
resSet.close();
stmt.close();
conn.close();
}
else{
Log.e(TAG, "selectAll", "table: ["+this.TABLE_NAME+"] does not exist");
}
}
您可以使用布尔变量:
boolean isEmpty = true;
while (resSet.next()) {
isEmpty = false;
Log.d(TAG, "selectAll", "ID: "+resSet.getString(ID_COL));
Log.d(TAG, "selectAll", "Node: "+resSet.getString(NODE_ID_COL));
Log.d(TAG, "selectAll", "Lat: "+resSet.getString(LAT_COL));
Log.d(TAG, "selectAll", "Lng: "+resSet.getString(LNG_COL));
Log.d(TAG, "selectAll", "xmlPath: "+resSet.getString(XML_PATH_COL));
}
从javadoc:
如果新的当前行有效,则为true;如果没有更多行,则为false
你可以试试这个
if(resSet.next())
{
do {
Log.d(TAG, "selectAll", "ID: "+resSet.getString(ID_COL));
Log.d(TAG, "selectAll", "Node: "+resSet.getString(NODE_ID_COL));
Log.d(TAG, "selectAll", "Lat: "+resSet.getString(LAT_COL));
Log.d(TAG, "selectAll", "Lng: "+resSet.getString(LNG_COL));
Log.d(TAG, "selectAll", "xmlPath: "+resSet.getString(XML_PATH_COL));
}
while (resSet.next())
}
else
{
// Message : No Data present
}
或者您可以尝试:
boolean empty = true;
while( rs.next() ) {
// ResultSet processing here
empty = false;
}
if( empty ) {
// Empty result set
}
如果ResultSet为空,res.next()将返回false,否则将返回true。因此,如果ResultSet为空,我使用的if语句将运行。如果数据存在,那么它将跳过第一行。@Harshit您可以使用
ResultSet.beforeFirst()
或ResultSet.first()
来获取第一行。很少发现do while
循环是最佳选择的情况,但这是其中之一。
ResultSet rs = statement.execute();
if (!rs.next()){
//ResultSet is empty
}
boolean empty = true;
while( rs.next() ) {
// ResultSet processing here
empty = false;
}
if( empty ) {
// Empty result set
}
if(!res.next()) // this would run if it's empty