java mysql count行数 [英] java mysql count number of rows

查看:93
本文介绍了java mysql count行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了这段代码,允许我计算表格中的行数。但是,我无法返回计数的数字,并显示无法从结果类型为void的方法返回值。有人能告诉我'我的错误在哪里?非常感谢!

I created this code to allow me calculate the number of rows in my table. However, I'm not able to return the counted number with an error saying "cannot return a value from method whose result type is void." Could someone show me where' my error? Thanks alot!

public void num() throws Exception {
  try {
      // This will load the MySQL driver, each DB has its own driver
      Class.forName("com.mysql.jdbc.Driver");
      // Setup the connection with the DB
      connect = DriverManager.getConnection("jdbc:mysql://localhost/testdb?"
      + "user=root&password=");

      // Statements allow to issue SQL queries to the database
      statement = connect.createStatement();
      resultSet = statement.executeQuery("select * from testdb.emg");
      int count = 0;
      while (resultSet.next()) {
        count++;
      }  
      return count;
  } catch (Exception e) {
  }


推荐答案

尝试以下代码

 public int num() throws Exception {
 try {
 // This will load the MySQL driver, each DB has its own driver
 Class.forName("com.mysql.jdbc.Driver");
 // Setup the connection with the DB
 connect = DriverManager.getConnection("jdbc:mysql://localhost/testdb?"
 + "user=root&password=");

 // Statements allow to issue SQL queries to the database
 statement = connect.createStatement();
 resultSet = statement.executeQuery("select count(*) from testdb.emg");

 while (resultSet.next()) {
 return resultSet.getInt(1);
 }
} catch (Exception e) {
}

以下是错误


  1. public void num()抛出异常{

应该是

public int num()抛出异常{

要计算总行数,您应该使用查询从testdb.emg中选择count(*)

For counting total rows you should use query select count(*) from testdb.emg

让我知道任何问题。

这篇关于java mysql count行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆