java mysql count number of rows

Try below code

 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) {
}

Below were error

  1. public void num() throws Exception {

    should be

    public int num() throws Exception {

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

Let me know incase of any problem.


Change

public void num() throws Exception {

to

public int num() throws Exception {

You are returning value from variable count which is of type int therefore the return type of the method should be int as well.

You should also make sure there is a return statement in every execution path through your code including the exception handler in the catch blocks (or you will get a "missing return statement" error message). However, it is best to avoid catch statements which catch all exceptions (like yours). Also, ignoring (i.e. not handling) exceptions in the catch block often leads to hard to diagnose problems and is a bad practice.

There are also other problems with the code: with the exception of count none of your variables have been declared.

Note that you may use the following SQL statement to obtain the number of rows directly:

select count(*) from testdb.emg

This avoids sending all of the data from table testdb.emg to your application and is much faster for big tables.


How to get count(*) mysql data table in java. TRY IT:

   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;
}

Tags:

Mysql

Sql

Java