How to Count Rows in MySQL

From Java Example Source Code

Jump to: navigation, search

Contents

[edit] Overview - How to Count Rows in MySQL

This Java example program shows how to count rows in mysql.

[edit] Java Source Code

  • Package: example.jdbc.mysql
  • File: CountRows_MySQL.java
package example.jdbc.mysql;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
 
public class CountRows_MySQL {
 
    public static Connection getConnection() throws Exception {
	String driver = "org.gjt.mm.mysql.Driver";
	String url = "jdbc:mysql://localhost/octopus";
	String username = "root";
	String password = "root";
 
	Class.forName(driver); // load MySQL driver
	Connection conn = DriverManager.getConnection(url, username, password);
	return conn;
    }
 
    public static int countRows(Connection conn, String tableName) throws SQLException {
	// select the number of rows in the table
	Statement stmt = null;
	ResultSet rs = null;
	int rowCount = -1;
	try {
	    stmt = conn.createStatement();
	    rs = stmt.executeQuery("SELECT COUNT(*) FROM " + tableName);
	    // get the number of rows from the result set
	    rs.next();
	    rowCount = rs.getInt(1);
	} finally {
	    rs.close();
	    stmt.close();
	}
	return rowCount;
    }
 
    public static void main(String[] args) {
	Connection conn = null;
	try {
	    conn = getConnection();
	    String tableName = "myTable";
	    System.out.println("tableName=" + tableName);
	    System.out.println("conn=" + conn);
	    System.out.println("rowCount=" + countRows(conn, tableName));
	} catch (Exception e) {
	    e.printStackTrace();
	    System.exit(1);
	} finally {
	    // release database resources
	    try {
		conn.close();
	    } catch (SQLException e) {
		e.printStackTrace();
	    }
	}
    }
}

[edit] What Result You Can Get

Coming soon...

[edit] Required External Libraries and/or Files for this Java Example

In order to run this Java example, one of the following libraries may be required: In order to run this example program, one of the following libraries may be required:


[edit] How to Run this Java Example Program

We recommend running this Java example program with Eclipse.

For assistance in working with Eclipse, please see How to Run Java Program with Eclipse.

It's fairly easy.



[edit] Question & Answer

Any question?

Click edit and post your question or answer here.


Personal tools