java mysql计算行数

Eug*_*ene 5 java mysql

我创建了这段代码,允许我计算表格中的行数.但是,我无法返回计数的数字,并显示"无法从结果类型为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) {
  }
Run Code Online (Sandbox Code Playgroud)

Fah*_*kar 17

试试下面的代码

 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) {
}
Run Code Online (Sandbox Code Playgroud)

以下是错误

  1. public void num() throws Exception {

    应该

    public int num() throws Exception {

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

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


Mar*_*cus 5

如何在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;
}
Run Code Online (Sandbox Code Playgroud)