askIT

Delete data from Java database table

document-save.png Download Java delete data from table - PostgreSQL code

This code show you how to delete a product from a database table. We want to delete Mint Latte from the table products.

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 deleteProduct

public void deleteProduct(String productName){
    System.out.println("CoffeShopDbImpl: deleteProduct " + productName);
    try {
        PreparedStatement st = conn.prepareStatement(
                    "DELETE FROM products " +
                            "WHERE product_name=?");

        st.setString(1, productName);
        st.executeUpdate();
        st.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
} // deleteProduct

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

        // Delete Mint Latte
        coffeShopDbImpl.deleteProduct("Mint Latte");


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