从 MySQL 中的结果集中获取行数?
Getting row count from ResultSet in MySQL?
我有一个通过 JDBC 连接到我的数据库的表单,我创建了一个方法,我打算打印出 table 中的行数,如下所示:
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;"
作为参数,它应该打印出我的 table 的行数。例如,如果我目前在 MyTable 中有 4 行,它应该打印 4
但它打印出来的只是一个带有随机数字和字母的对象:
com.mysql.jdbc.JDBC42ResultSet@7e11fc40
如何在将 sql 查询结果传递给我的函数后显示它?
r.getInt("totalCount");
将查询更改为 "Select COUNT(*) as totalCount FROM MyTable;"
如果要使用printThis
,将r
作为参数传入函数,并在结果集中使用getInt
方法获取函数内的整数值。
由于结果集只包含一列,您可以简单地使用列索引号 1。
r.getInt(1);
你必须换到这一行printThis.println(r.toString());
并添加为 printThis.println(r.getInt(1));
或 System.out.println(r.getInt(1));
我有一个通过 JDBC 连接到我的数据库的表单,我创建了一个方法,我打算打印出 table 中的行数,如下所示:
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;"
作为参数,它应该打印出我的 table 的行数。例如,如果我目前在 MyTable 中有 4 行,它应该打印 4
但它打印出来的只是一个带有随机数字和字母的对象:
com.mysql.jdbc.JDBC42ResultSet@7e11fc40
如何在将 sql 查询结果传递给我的函数后显示它?
r.getInt("totalCount");
将查询更改为 "Select COUNT(*) as totalCount FROM MyTable;"
如果要使用printThis
,将r
作为参数传入函数,并在结果集中使用getInt
方法获取函数内的整数值。
由于结果集只包含一列,您可以简单地使用列索引号 1。
r.getInt(1);
你必须换到这一行printThis.println(r.toString());
并添加为 printThis.println(r.getInt(1));
或 System.out.println(r.getInt(1));