java mysql count行数

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

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() throws Exception {

    应该

    public int num() throws Exception {

  2. 要计算总行数,您应该使用select count(*) from testdb.emg查询select count(*) from testdb.emg

如有任何问题,请告诉我。

更改

 public void num() throws Exception { 

 public int num() throws Exception { 

您将从类型为int变量count返回值,因此该方法的返回类型也应为int

您还应确保在代码的每个执行路径中都有一个return语句,包括catch块中的exception处理程序(或者您将收到“缺少返回语句”错误消息)。 但是,最好避免捕获所有exception的catch语句(如您的)。 此外,忽略(即不处理)catch块中的exception通常会导致难以诊断问题,这是一种不好的做法。

代码还有其他问题:除了count之外,没有声明任何变量。

请注意,您可以使用以下SQL语句直接获取行数:

 select count(*) from testdb.emg 

这样可以避免将表testdb.emg所有数据发送到您的应用程序,并且对于大表来说要快得多。

如何在java中获取count(*)mysql数据表。 试试吧:

  public int getRowNumber(){ int numberRow = 0; Connection mysqlConn = DriverManager.getConnection(HOST, USER_ID, PASSWORD); try{ mysqlConn.getConnection(); String query = "select count(*) from dataTable"; PreparedStatement st = mysqlConn.preparedStatement(query); ResultSet rs = st.executeQuery(); while(rs.next()){ numberRow = rs.getInt("count(*)"); } }catch (Exception ex){ System.out.println(ex.getMessage()); } return numberRow; } 
 public void num() throws Exception { 

应该

 public int num() throws Exception {