askIT

Count rows in Java database table

Use the count(*) to count the number of rows in a table.

An example query to count the number of rows in products table is:
SELECT count(*) FROM products.

We create a method named countRows()


public int countRows(){
    try {
        PreparedStatement st = conn.prepareStatement(
                "SELECT count(*) FROM products");
        ResultSet rs = st.executeQuery();
        while (rs.next()){
            return rs.getInt(1);
        }
        rs.close();
        st.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }

    return -1;
} // countRows

Now call the method from your main class:

package com.nettport.coffeshop;

import com.nettport.coffeshop.dao.CoffeShopDbImpl;

public class Main {

    public static void main(String[] args) {
        // Connect
        CoffeShopDbImpl coffeShopDbImpl = new CoffeShopDbImpl();
        coffeShopDbImpl.connect();

        // Create tables
        coffeShopDbImpl.createTables();

        // Insert products
        /*
        coffeShopDbImpl.insertProduct("Espresso", 0.40);
        coffeShopDbImpl.insertProduct("Americano", 0.65);
        coffeShopDbImpl.insertProduct("Latte", 2.00);
        coffeShopDbImpl.insertProduct("Cappuccino", 2.40);
        coffeShopDbImpl.insertProduct("Almond Cappuccino", 1.90);
        coffeShopDbImpl.insertProduct("Mint Latte", 4.90);
        coffeShopDbImpl.insertProduct("Coffee Frappe", 0.60);
        coffeShopDbImpl.insertProduct("Ice Coffee", 2.10);
        */


        // Update price
        /*
        coffeShopDbImpl.updateProductPrice("Espresso", 0.50);
        coffeShopDbImpl.updateProductPrice("Cappuccino", 2.60);
        */


        // Get number of rows
        int numberOfRows = coffeShopDbImpl.countRows();
        System.out.println("Rows" + numberOfRows);


        // Disconnect
        coffeShopDbImpl.disconnect();

    }
}

Add comment

avatar_blank_60.png

Comment:

Name:

Email:

Comments

No comments yet. You can be the first one to comment. Just write your comment in the form and click on the submit button.