如何检查Resultset是否为空

时间:2015-08-11 11:17:26

标签: java sqlite jdbc

我编写了下面的代码来检索表中的所有记录,但是当我创建一个新表时,我想检查ResultSet是否为空,如果它是空的则显示消息。

我该怎么做

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");
    }

}

5 个答案:

答案 0 :(得分:2)

您可以使用布尔变量:

    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));
    }

答案 1 :(得分:2)

boolean isEmpty = resSet.next()

来自javadoc:

  

如果新的当前行有效,则为true;如果没有更多行,则为false

答案 2 :(得分:2)

你可以试试这个

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   
}

答案 3 :(得分:1)

A         B        c         D
234567    local    234567    local

或者您可以尝试:

ResultSet rs = statement.execute();
if (!rs.next()){
//ResultSet is empty
}

答案 4 :(得分:1)

if(!res.next()) // this would run if it's empty

如果ResultSet为空,res.next()将返回false,否则返回true。因此,如果ResultSet为空,我使用的if语句将会运行。