How to Count Records by Using PreparedStatement

From Java Example Source Code

Jump to: navigation, search

Contents

[edit] Overview - How to Count Records by Using PreparedStatement

This Java example program shows how to Count Records by using PreparedStatement.

[edit] Java Source Code

  • Package: example.jdbc.preparedstatement
  • File: CountRecordsUsingPreparedStatement.java
package example.jdbc.preparedstatement;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
 
public class CountRecordsUsingPreparedStatement {
    public static Connection getConnection() throws Exception {
	String driver = "oracle.jdbc.driver.OracleDriver";
	String url = "jdbc:oracle:thin:@localhost:1521:databaseName";
	String username = "name";
	String password = "password";
	Class.forName(driver);
	Connection conn = DriverManager.getConnection(url, username, password);
	return conn;
    }
 
    public static void main(String[] args) {
	ResultSet rs = null;
	Connection conn = null;
	PreparedStatement pstmt = null;
	try {
	    conn = getConnection();
	    String query = "select count(*) from tableName";
	    pstmt = conn.prepareStatement(query);
	    rs = pstmt.executeQuery();
	    if (rs.next()) {
		int numberOfRows = rs.getInt(1);
		System.out.println("numberOfRows= " + numberOfRows);
	    } else {
		System.out.println("error: could not get the record counts");
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	} finally {
	    try {
		rs.close();
		pstmt.close();
		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