askIT

Insert data into Java database table

document-save.png Download Java insert data into table PostgreSQL code

We want to insert our products into the product database table.

Our products that we want to insert into the table:

We create a method named insertProduct in our CoffeShopDbImpl class.

package com.nettport.coffeshop.dao;

import java.sql.PreparedStatement;
import java.sql.SQLException;

public class CoffeShopDbImpl extends DbAdapter {

    /**
    * Insert a new product into the table products
    * @param productName
    * @param productPrice
    */

    public void insertProduct(String productName, Double productPrice){
        System.out.println("CoffeShopDbImpl: insertProduct " + productName + " $" + productPrice);
        try {
            PreparedStatement st = conn.prepareStatement(
                    "INSERT INTO products " +
                            "(product_name, product_price) " +
                            "VALUES(?,?)");

            st.setString(1, productName);
            st.setDouble(2, productPrice);
            st.executeUpdate();
            st.close();

        } catch (SQLException e) {
            e.printStackTrace();
        }
    } // insertProduct

    /**
    * Creates all necessary tables for coffe store
    */

    public void createTables(){
        System.out.println("CoffeShopDbImpl: Create tables");
        try {
            stmt = conn.createStatement();
            String sql = "CREATE TABLE IF NOT EXISTS products " +
                    "(product_id SERIAL PRIMARY KEY NOT NULL," +
                    " product_name VARCHAR(100) NOT NULL, " +
                    " product_price REAL)";
            stmt.executeUpdate(sql);
            stmt.close();

        } catch (SQLException e) {
            e.printStackTrace();
        }
    } // createTables


}

We call the method insertProduct from the 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);

        // Disconnect
        coffeShopDbImpl.disconnect();

    }
}

DbAdapter

The DbAdapter class i nessesary to make the code run.

package com.nettport.coffeshop.dao;

import java.sql.*;

public class DbAdapter {

    /* 01 Variables ---------------------------------------- */
    String jdbcUrl = "jdbc:postgresql://localhost:5432/coffe_shop";
    String username = "postgres";
    String password = "postgre";

    /* 02 Database variables ------------------------------- */
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;

    /* 03 Constructor for DbAdapter ------------------------ */
    public DbAdapter() {
    }

    /**
    * Connect to a database
    */

    public void connect() {
        try {
            // Step 2 - Open connection
            conn = DriverManager.getConnection(jdbcUrl, username, password);

            // Print connected
            System.out.println("DbAdapter: Connection to database established");

        } catch (SQLException e) {
            e.printStackTrace();
        }
    } // connect

    /**
    * Disconnect from database
    */

    public void disconnect() {
        try {

            // Step 5 Close connection
            if (stmt != null) {
                stmt.close();
            }
            if (rs != null) {
                rs.close();
            }
            if (conn != null) {
                conn.close();
            }
            // Print connected
            System.out.println("DbAdapter: Connection to database closed");

        } catch (Exception e) {
            e.printStackTrace();
        }
    } // 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.