Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从MySQL中的ResultSet获取行数?_Java_Mysql_Database_Count_Resultset - Fatal编程技术网

Java 从MySQL中的ResultSet获取行数?

Java 从MySQL中的ResultSet获取行数?,java,mysql,database,count,resultset,Java,Mysql,Database,Count,Resultset,我有一个表单,它通过JDBC连接到我的数据库,我创建了一个方法,我打算将表中的行数打印出来,如下所示: public static void getRowCount(String sql, PrintWriter printThis) { try { Connection c = // Another function called from a different class that handles the connection PreparedSta

我有一个表单,它通过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字符串
“从MyTable;”“
中选择COUNT(*)作为参数,则它应该打印出表的行数。例如,如果我当前在MyTable中有4行,它应该打印
4
,但它打印出来的只是一个带有随机数字和字母的对象:

com.mysql.jdbc.JDBC42ResultSet@7e11fc40
在将sql查询的结果传递给函数后,如何显示该结果

 r.getInt("totalCount");
将查询更改为“从MyTable中选择COUNT(*)作为totalCount;”“


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

因为resultset将只包含一列,所以只需使用列索引号1即可


r.getInt(1)

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

并添加为this
printThis.println(r.getInt(1))
系统输出println(r.getInt(1))