askIT

Update data into Java database table

document-save.png Download Java update table PostgreSQL code

The prices of diffrent products have changed, so we need to update them. Lets create a method for updating prices.

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 updateProductPrice

public void updateProductPrice(String productName, Double newProductPrice){
    System.out.println("CoffeShopDbImpl: updateProductPrice " + productName +
        " - new price :$" + newProductPrice);
    try {
        PreparedStatement st = conn.prepareStatement(
                    "UPDATE products SET product_price=?" +
                            "WHERE product_name=?");

        st.setString(1, productName);
        st.setDouble(2, newProductPrice);
        st.executeUpdate();
        st.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
} // updateProductPrice

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);


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