Slip No 12 Q A

Write a java program to count the number of records in a table.

import java.sql.*;

public class CountRecords {

    public static void main(String[] args) {

        String url = "jdbc:mysql://localhost:3306/college"; // change DB name
        String user = "root";       // DB username
        String password = "root";   // DB password

        try {
            // 1. Load JDBC Driver
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 2. Establish Connection
            Connection con = DriverManager.getConnection(url, user, password);

            // 3. SQL Query to count records
            String sql = "SELECT COUNT(*) FROM student";

            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(sql);

            // 4. Retrieve count
            if (rs.next()) {
                int count = rs.getInt(1);
                System.out.println("Total number of records: " + count);
            }

            // 5. Close resources
            rs.close();
            stmt.close();
            con.close();

        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top