askIT

Select specific data list from Java database table

document-save.png Download java select specific data from list java database table code

If we want to get all product names, or product prices we can do this by giving a SQL
SELECT product_price FROM products.
It will give a resultset that we can add to a list.

Our products table:

product_id product_name product_price
1 Espresso $0.40
2 Americano $0.65
3 Latte $2.00
3 Cappuccino $2.40
5 Mocha Coffe $1.30
4 Almond Cappuccino $1.90
6 Mint Latte $4.90
5 Coffee Frappe $0.60
7 Ice Coffee $2.10

We create a method named queryProductPrice

/**
* Gives all product prices
* @return
*/

public List queryProductPrice(){

    List pricesList = new ArrayList<>();

    try {
        PreparedStatement st = conn.prepareStatement(
                    "SELECT product_price FROM products");
        ResultSet rs = st.executeQuery();
        while (rs.next()){
            double price = rs.getDouble(1);
            pricesList.add(price);
        }
        rs.close();
        st.close();

    } catch (SQLException e) {
        e.printStackTrace();
    }
    return pricesList;
} // queryProductPrice

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 all prices
        List allPricesList = coffeShopDbImpl.queryProductPrice();
        int i = 0;
        while (i < allPricesList.size()) {
            System.out.println(allPricesList.get(i));
            i++;
        }

        // 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.