【问题标题】:How to verify if my JDBC query output has data in it or not如何验证我的 JDBC 查询输出中是否包含数据
【发布时间】:2022-11-02 15:14:37
【问题描述】:

我想验证我的 JDBC 查询输出中是否有数据。如果它不包含任何数据,那么它应该将断言打印为假。

我试过用这个:

System.out.println("Table contains "+rs.getRow()+" rows");
if (!rs.next())
{
    Assert.assertTrue(false);
}
else
{
    Assert.assertTrue(true);
}

我尝试使用如下:

System.out.println("Table contains "+rs.getRow()+" rows");

if (!rs.next())
{
    Assert.assertTrue(false);
}
else
{
    Assert.assertTrue(true);
}

但它没有用。那么有人可以建议如何解决这个问题吗?

【问题讨论】:

  • “但它没有用” - 你能解释为什么吗?你期望从中得到什么输出,它给你的实际输出是什么?

标签: jdbc


【解决方案1】:

如果您只需要知道一个表中有多少行,让 DBMS 计算它们:

select count(*) as noRows from table

在您的 java 代码中,它看起来像这样 sn-p

boolean hasRows= false;
Statement stmt = null;
ResultSet rs   = null;
try {
   stmt = connection.createStatement();
   rs   = stmt.executeQuery("select count(*) as noRows from table");
   if ( rs.next() ) {
      if ( rs.getInt(1) > 0 ) {
          hasRows = true;
     }
   }
} catch (SQLException sqlex ) {
   // print or log an error message
} finally {
   if ( rs != null ) {
     try { 
        rs.close();
     } catch (SQlException sqlex ) {
        // print or log an error message
     }
   }
   if ( stmt != null ) {
     try { 
        stmt.close();
     } catch (SQlException sqlex ) {
        // print or log an error message
     }
   }
}
Assert.assertTrue(hasRows);

关闭连接也很有意义。 这将只返回表中的行。如果您需要知道特定查询的大小,我自己也会对查询进行类似的操作,只需使用 count(*) 或 count(DISTINCT xyz) 命令替换查询中的字段。首先在您的 sql 监视器中尝试一下,因为如果查询运行时间过长,您可能会不高兴。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多