Stock Management System project in Java and MySQL with source code

Managing stock is an important aspect of any business. The Stock Management System is an application that helps manage the stock of a business. The system allows users to add products, list products, and perform stock in and stock out transactions. In this article, we will go through the code of the simple Stock Management System Project in java, which is implemented using Java and MySQL and you have copy the source code.

Stock Management System project in Java and MySQL with source code


The code of the Stock Management System starts with importing the required java implementing packages:


import java.sql.*;
import java.util.Scanner;



$ads={1}


The 'java.sql.*' package is required for connecting to the MySQL database, executing SQL queries, and handling exceptions. The 'java.util.Scanner' package is required for taking user input.

The 'StockManagementSystem' class is the 'main' class of the application, which contains the main method:



public class StockManagementSystem {
    public static void main(String[] args) {
        // Code goes here
    }
}


The 'main' method starts by creating a 'Scanner' object for taking user input:



Scanner scanner = new Scanner(System.in);


Next, the code tries to establish a connection with the MySQL database using the 'DriverManager' class:



Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/stockmanagement", "root", "");



The above line of code establishes a connection with the MySQL database named 'stockmanagement' running on the local machine using the username 'root' and an empty password. If the connection is successful, a 'Connection' object is returned, which is used to execute SQL queries.

The 'Statement' object is used to execute SQL queries on the database. The code creates a Statement object from the 'Connection' object:



Statement statement = connection.createStatement();  
  


The above line of code creates a 'Statement' object, which is used to execute SQL queries on the 'connection' object.

The next block of code creates the required tables if they do not exist in the database:


// Create tables if they do not exist
            statement.executeUpdate("CREATE TABLE IF NOT EXISTS products (id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(50) NOT NULL, quantity INT NOT NULL, price DECIMAL(10, 2) NOT NULL)");
            statement.executeUpdate("CREATE TABLE IF NOT EXISTS transactions (id INT PRIMARY KEY AUTO_INCREMENT, product_id INT NOT NULL, quantity INT NOT NULL, transaction_date DATE NOT NULL, transaction_type VARCHAR(10) NOT NULL)");


The above code creates two tables named 'products' and 'transactions'. The products table contains information about the products such as 'id', 'name', 'quantity', and 'price'. The transactions table contains information about the transactions such as 'id', 'product_id', 'quantity', 'transaction_date', and 'transaction_type'.


while (true) {
    System.out.println("\n=== STOCK MANAGEMENT SYSTEM ===");
    System.out.println("1. Add Product");
    System.out.println("2. List Products");
    System.out.println("3. Stock In");
    System.out.println("4. Stock Out");
    System.out.println("5. Exit");
    System.out.print("Enter your choice: ");

    int choice = scanner.nextInt();

    // Code goes here
}



Stock Management System project in Java and MySQL with source code


The above code displays a menu with five options: Add Product, List Products, Stock In, Stock Out, and Exit. The user is prompted to enter a choice, which is stored in the choice variable.

The program then enters a 'while loop' which displays a menu of options to the user. The available options are:

Add Product: Allows the user to add a new product to the products table. List Products: Lists all the products currently in the products table. Stock In: Adds stock to an existing product in the products table and records the transaction in the transactions table. Stock Out: Removes stock from an existing product in the products table and records the transaction in the transactions table. Exit: Exits the program.


The user's choice is read using the 'Scanner.nextInt()' method, and a switch statement is used to determine which action to take.

For option 1, the user is prompted to enter the details of the new product (name, quantity, and price). The program then inserts a new row into the 'products' table using an SQL 'INSERT INTO' statement.

Stock Management System project in Java and MySQL with source code


For option 2, the program retrieves all rows from the 'products' table using an SQL 'SELECT' statement, and displays the results to the user.

For option 3, the user is prompted to enter the ID of the product they want to add stock to, and the quantity of stock to add. The program then updates the corresponding row in the 'products' table using an SQL 'UPDATE' statement, and inserts a new row into the 'transactions' table to record the transaction.

For option 4, the user is prompted to enter the ID of the product they want to remove stock from, and the quantity of stock to remove. The program first checks if there is enough stock of the product before removing the specified quantity. If there is enough stock, the program updates the corresponding row in the 'products' table using an SQL 'UPDATE' statement, and inserts a new row into the 'transactions' table to record the transaction. If there is not enough stock, an error message is displayed to the user.

Stock Management System project in Java and MySQL with source code


For Option 5, simply exits the program using the 'System.exit()' method.


import java.sql.*;
import java.util.Scanner;

public class StockManagementSystem {
    /**
     * @param args
     */
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        try {
            

            // Connect to XAMPP SQL Server
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/stockmanagement", "root", "");
            Statement statement = connection.createStatement();

            // Create tables if they do not exist
            statement.executeUpdate("CREATE TABLE IF NOT EXISTS products (id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(50) NOT NULL, quantity INT NOT NULL, price DECIMAL(10, 2) NOT NULL)");
            statement.executeUpdate("CREATE TABLE IF NOT EXISTS transactions (id INT PRIMARY KEY AUTO_INCREMENT, product_id INT NOT NULL, quantity INT NOT NULL, transaction_date DATE NOT NULL, transaction_type VARCHAR(10) NOT NULL)");

            // Display menu
            while (true) {
                System.out.println("\n=== STOCK MANAGEMENT SYSTEM ===");
                System.out.println("1. Add Product");
                System.out.println("2. List Products");
                System.out.println("3. Stock In");
                System.out.println("4. Stock Out");
                System.out.println("5. Exit");
                System.out.print("Enter your choice: ");

                int choice = scanner.nextInt();

                switch (choice) {
                    case 1:
                        System.out.print("Enter product name: ");
                        String name = scanner.next();

                        System.out.print("Enter product quantity: ");
                        int quantity = scanner.nextInt();

                        System.out.print("Enter product price: ");
                        double price = scanner.nextDouble();

                        // Insert new product into the products table
                        statement.executeUpdate("INSERT INTO products (name, quantity, price) VALUES ('" + name + "', " + quantity + ", " + price + ")");
                        System.out.println("Product added successfully.");
                        break;

                    case 2:
                        // List all products from the products table
                        ResultSet resultSet = statement.executeQuery("SELECT * FROM products");
                        while (resultSet.next()) {
                            int productId = resultSet.getInt("id");
                            String productName = resultSet.getString("name");
                            int productQuantity = resultSet.getInt("quantity");
                            double productPrice = resultSet.getDouble("price");
                            System.out.println("ID: " + productId + " | Name: " + productName + " | Quantity: " + productQuantity + " | Price: " + productPrice);
                        }
                        break;

                    case 3:
                        System.out.print("Enter product ID: ");
                        int productIdIn = scanner.nextInt();

                        System.out.print("Enter quantity: ");
                        int quantityIn = scanner.nextInt();

                        // Update quantity of the product with the given ID in the products table
                        statement.executeUpdate("UPDATE products SET quantity = quantity + " + quantityIn + " WHERE id = " + productIdIn);

                        // Insert a new transaction record into the transactions table
                        statement.executeUpdate("INSERT INTO transactions (product_id, quantity, transaction_date, transaction_type) VALUES (" + productIdIn + ", " + quantityIn + ", NOW(), 'IN')");
                        System.out.println("Stock in transaction recorded successfully.");
                        break;

                    case 4:
                        System.out.print("Enter product ID: ");
                        int productIdOut = scanner.nextInt();

                        System.out.print("Enter quantity: ");
                        int quantityOut = scanner.nextInt();

                        // Check if there is enough quantity of the product in the products table
                        ResultSet productResult = statement.executeQuery("SELECT * FROM products WHERE id = " + productIdOut);
                        if (productResult.next()) {
                            int productQuantity = productResult.getInt("quantity");
                            if (quantityOut > productQuantity) {
                                System.out.println("Error: Not enough stock");
                                                    } else {
                        // Update quantity of the product with the given ID in the products table
                        statement.executeUpdate("UPDATE products SET quantity = quantity - " + quantityOut + " WHERE id = " + productIdOut);

                        // Insert a new transaction record into the transactions table
                        statement.executeUpdate("INSERT INTO transactions (product_id, quantity, transaction_date, transaction_type) VALUES (" + productIdOut + ", " + quantityOut + ", NOW(), 'OUT')");
                        System.out.println("Stock out transaction recorded successfully.");
                    }}
                    break;

                case 5:
                    // Exit the program
                    System.exit(0);
                    break;

                default:
                    System.out.println("Invalid choice. Please enter a valid choice.");
            }
        }
    } catch (SQLException e) {
        System.out.println("Error: " + e.getMessage());
    }
}
    }



In summary, this code provides a basic implementation of a simple stock management system using a MySQL database. It demonstrates the use of SQL statements to manipulate data in a database, and provides a simple command-line interface for the user to interact with the system.

Previous Post Next Post