Count Records using the Prepared Statement in Java

Description

The following code shows how to count Records using the Prepared Statement.

Example


    //from   www  .j av  a2 s .  com


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class Main {
  public static void main(String[] argv) throws Exception {

    int records = 0;

    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctutorial",
        "root", "root");

    String sql = "SELECT COUNT(*) FROM mytable" ;
    PreparedStatement prest = con.prepareStatement(sql);
    ResultSet rs = prest.executeQuery();
    while (rs.next()) {
      records = rs.getInt(1);
    }
    System.out.println("Number of records: " + records);
    con.close();
  }
}




















Home »
  Java Tutorial »
    JDBC »




Batch
Binary Data
Database
Date Time
Insert
ResultSet
SQL
Statement
Stored Function
Table