【问题标题】:Getting row count from ResultSet in MySQL?从 MySQL 中的 ResultSet 获取行数?
【发布时间】:2018-06-11 08:52:17
【问题描述】:

我有一个通过 JDBC 连接到我的数据库的表单,我创建了一个方法,我打算打印出我的表中的行数,如下所示:

public static void getRowCount(String sql, PrintWriter printThis)
{
   try
   {
       Connection c = // Another function called from a different class that handles the connection
       PreparedStatement p = (PreparedStatement) connect.prepareStatement(sql);
       ResultSet r = p.executeQuery();

       while (r.next())
       {
           printThis.println(r.toString());
       }
        c.close();
   }

   catch (Exception e)
   {
        e.printStackTrace();
   }
}

如果我传递一个 sql 字符串 "Select COUNT(*) FROM MyTable;" 作为参数,它应该打印出我的表的行数。例如,如果我当前在 MyTable 中有 4 行,它应该打印 4 但它打印出来的只是一个带有随机数字和字母的对象:

com.mysql.jdbc.JDBC42ResultSet@7e11fc40

将我的 sql 查询的结果传递给我的函数后如何显示它?

【问题讨论】:

    标签: java mysql database count resultset


    【解决方案1】:
     r.getInt("totalCount");
    

    将查询更改为"Select COUNT(*) as totalCount FROM MyTable;"

    如果要使用printThis,请将r作为参数传递到函数中,并在结果集中使用getInt方法获取函数内的整数值。

    【讨论】:

      【解决方案2】:

      由于结果集将只包含一列,因此您可以简单地使用列索引号 1。

      r.getInt(1);

      【讨论】:

        【解决方案3】:

        您必须更改为此行printThis.println(r.toString());

        并添加为 printThis.println(r.getInt(1));System.out.println(r.getInt(1));

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-06-25
          • 2010-09-25
          • 1970-01-01
          • 2018-07-19
          • 2012-01-07
          • 2014-12-26
          • 2017-10-06
          • 2013-03-26
          相关资源
          最近更新 更多