Home Database Mysql Tutorial How to develop a simple online ordering system using MySQL and Java

How to develop a simple online ordering system using MySQL and Java

Sep 21, 2023 pm 04:27 PM
mysql java Online ordering system

How to develop a simple online ordering system using MySQL and Java

How to use MySQL and Java to develop a simple online ordering system

In recent years, with the development of the Internet, more and more restaurants have begun to order online. Meal model transformation. The online ordering system can not only improve the service efficiency of the restaurant, but also facilitate customers to order food, and realize online payment, takeout delivery and other functions. This article will introduce how to use MySQL and Java to develop a simple online ordering system to meet the needs of restaurants and customers.

1. Database design

Before developing the online ordering system, you first need to design the database structure. The following is a simplified database design example:

  1. User table (User): Contains user ID, user name, password and other fields.
  2. Dish table (Dish): Contains fields such as dish ID, dish name, price, and description.
  3. Order table (Order): includes fields such as order ID, user ID, order time, total amount, etc.
  4. Order Detail (OrderDetail): Contains order detail ID, order ID, dish ID, quantity and other fields.

The above is a simple database design that can be expanded according to actual needs.

2. Java back-end development

  1. Database connection

Using Java language to connect to the MySQL database requires the introduction of relevant database driver packages. First, add the MySQL driver package to the project, and then establish a database connection in the code. The sample code is as follows:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DatabaseConnector {
    private static final String URL = "jdbc:mysql://localhost:3306/online_ordering_system";
    private static final String USER = "root";
    private static final String PASSWORD = "123456";

    public static Connection getConnection() throws SQLException {
        Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
        return connection;
    }
}
Copy after login
  1. User management

User management includes user registration and login and other functions. The sample code is as follows:

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserManager {
    public static boolean register(String username, String password) throws SQLException {
        Connection connection = DatabaseConnector.getConnection();
        PreparedStatement statement = connection.prepareStatement("INSERT INTO User (username, password) VALUES (?, ?)");
        statement.setString(1, username);
        statement.setString(2, password);
        int rows = statement.executeUpdate();
        statement.close();
        connection.close();
        return rows > 0;
    }

    public static boolean login(String username, String password) throws SQLException {
        Connection connection = DatabaseConnector.getConnection();
        PreparedStatement statement = connection.prepareStatement("SELECT * FROM User WHERE username = ? AND password = ?");
        statement.setString(1, username);
        statement.setString(2, password);
        ResultSet resultSet = statement.executeQuery();
        boolean result = resultSet.next();
        statement.close();
        connection.close();
        return result;
    }
}
Copy after login
  1. Dish management

Dish management includes functions such as adding dishes and querying them. The sample code is as follows:

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DishManager {
    public static boolean addDish(String dishName, double price, String description) throws SQLException {
        Connection connection = DatabaseConnector.getConnection();
        PreparedStatement statement = connection.prepareStatement("INSERT INTO Dish (dish_name, price, description) VALUES (?, ?, ?)");
        statement.setString(1, dishName);
        statement.setDouble(2, price);
        statement.setString(3, description);
        int rows = statement.executeUpdate();
        statement.close();
        connection.close();
        return rows > 0;
    }

    public static List<Dish> getDishes() throws SQLException {
        Connection connection = DatabaseConnector.getConnection();
        PreparedStatement statement = connection.prepareStatement("SELECT * FROM Dish");
        ResultSet resultSet = statement.executeQuery();
        List<Dish> dishes = new ArrayList<>();
        while (resultSet.next()) {
            Dish dish = new Dish();
            dish.setDishId(resultSet.getInt("dish_id"));
            dish.setDishName(resultSet.getString("dish_name"));
            dish.setPrice(resultSet.getDouble("price"));
            dish.setDescription(resultSet.getString("description"));
            dishes.add(dish);
        }
        statement.close();
        connection.close();
        return dishes;
    }
}
Copy after login
  1. Order Management

Order management includes order creation, query and other functions. The sample code is as follows:

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

public class OrderManager {
    public static boolean createOrder(int userId, List<OrderDetail> orderDetails) throws SQLException {
        Connection connection = DatabaseConnector.getConnection();
        PreparedStatement statement = connection.prepareStatement("INSERT INTO Order (user_id, order_time, total_amount) VALUES (?, ?, ?)");
        statement.setInt(1, userId);
        statement.setTimestamp(2, new Timestamp(System.currentTimeMillis()));
        double totalAmount = 0;
        for (OrderDetail orderDetail : orderDetails) {
            totalAmount += orderDetail.getQuantity() * orderDetail.getDish().getPrice();
        }
        statement.setDouble(3, totalAmount);
        int rows = statement.executeUpdate();
        statement.close();

        if (rows > 0) {
            // 获取刚插入的订单ID
            PreparedStatement getLastInsertIdStatement = connection.prepareStatement("SELECT LAST_INSERT_ID()");
            ResultSet resultSet = getLastInsertIdStatement.executeQuery();
            int orderId = 0;
            if (resultSet.next()) {
                orderId = resultSet.getInt(1);
            }

            // 插入订单明细
            PreparedStatement insertOrderDetailStatement = connection.prepareStatement("INSERT INTO OrderDetail (order_id, dish_id, quantity) VALUES (?, ?, ?)");
            for (OrderDetail orderDetail : orderDetails) {
                insertOrderDetailStatement.setInt(1, orderId);
                insertOrderDetailStatement.setInt(2, orderDetail.getDish().getDishId());
                insertOrderDetailStatement.setInt(3, orderDetail.getQuantity());
                insertOrderDetailStatement.addBatch();
            }
            insertOrderDetailStatement.executeBatch();
            insertOrderDetailStatement.close();
            getLastInsertIdStatement.close();
        }

        connection.close();
        return rows > 0;
    }

    public static List<Order> getOrders(int userId) throws SQLException {
        Connection connection = DatabaseConnector.getConnection();
        PreparedStatement statement = connection.prepareStatement("SELECT * FROM Order WHERE user_id = ?");
        statement.setInt(1, userId);
        ResultSet resultSet = statement.executeQuery();
        List<Order> orders = new ArrayList<>();
        while (resultSet.next()) {
            Order order = new Order();
            order.setOrderId(resultSet.getInt("order_id"));
            order.setUserId(resultSet.getInt("user_id"));
            order.setOrderTime(resultSet.getTimestamp("order_time"));
            order.setTotalAmount(resultSet.getDouble("total_amount"));
            orders.add(order);
        }
        statement.close();
        connection.close();
        return orders;
    }
}
Copy after login

The above is a simple Java back-end development example, including user management, dish management, order management and other functions.

3. Front-end development

The front-end development part can be developed using HTML, CSS, JavaScript and other related technologies to implement user interface and interaction logic. No specific front-end code examples are provided here. It is recommended to use front-end frameworks such as Bootstrap for rapid development.

4. Summary

Using MySQL and Java to develop a simple online ordering system can improve the ordering experience of restaurants and customers. By rationally designing the database structure and using Java and MySQL for back-end development, functions such as user management, dish management, and order management can be realized. At the same time, front-end development also needs to consider the design of the user interface and the implementation of interaction logic.

I hope this article can help readers understand how to use MySQL and Java to develop a simple online ordering system, and provides some specific code examples for reference.

The above is the detailed content of How to develop a simple online ordering system using MySQL and Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Explain the purpose of foreign keys in MySQL. Explain the purpose of foreign keys in MySQL. Apr 25, 2025 am 12:17 AM

In MySQL, the function of foreign keys is to establish the relationship between tables and ensure the consistency and integrity of the data. Foreign keys maintain the effectiveness of data through reference integrity checks and cascading operations. Pay attention to performance optimization and avoid common errors when using them.

SQL vs. MySQL: Clarifying the Relationship Between the Two SQL vs. MySQL: Clarifying the Relationship Between the Two Apr 24, 2025 am 12:02 AM

SQL is a standard language for managing relational databases, while MySQL is a database management system that uses SQL. SQL defines ways to interact with a database, including CRUD operations, while MySQL implements the SQL standard and provides additional features such as stored procedures and triggers.

Compare and contrast MySQL and MariaDB. Compare and contrast MySQL and MariaDB. Apr 26, 2025 am 12:08 AM

The main difference between MySQL and MariaDB is performance, functionality and license: 1. MySQL is developed by Oracle, and MariaDB is its fork. 2. MariaDB may perform better in high load environments. 3.MariaDB provides more storage engines and functions. 4.MySQL adopts a dual license, and MariaDB is completely open source. The existing infrastructure, performance requirements, functional requirements and license costs should be taken into account when choosing.

What does 'platform independence' mean in the context of Java? What does 'platform independence' mean in the context of Java? Apr 23, 2025 am 12:05 AM

Java's platform independence means that the code written can run on any platform with JVM installed without modification. 1) Java source code is compiled into bytecode, 2) Bytecode is interpreted and executed by the JVM, 3) The JVM provides memory management and garbage collection functions to ensure that the program runs on different operating systems.

How does MySQL differ from Oracle? How does MySQL differ from Oracle? Apr 22, 2025 pm 05:57 PM

MySQL is suitable for rapid development and small and medium-sized applications, while Oracle is suitable for large enterprises and high availability needs. 1) MySQL is open source and easy to use, suitable for web applications and small and medium-sized enterprises. 2) Oracle is powerful and suitable for large enterprises and government agencies. 3) MySQL supports a variety of storage engines, and Oracle provides rich enterprise-level functions.

MySQL: The Database, phpMyAdmin: The Management Interface MySQL: The Database, phpMyAdmin: The Management Interface Apr 29, 2025 am 12:44 AM

MySQL and phpMyAdmin can be effectively managed through the following steps: 1. Create and delete database: Just click in phpMyAdmin to complete. 2. Manage tables: You can create tables, modify structures, and add indexes. 3. Data operation: Supports inserting, updating, deleting data and executing SQL queries. 4. Import and export data: Supports SQL, CSV, XML and other formats. 5. Optimization and monitoring: Use the OPTIMIZETABLE command to optimize tables and use query analyzers and monitoring tools to solve performance problems.

Composer: Aiding PHP Development Through AI Composer: Aiding PHP Development Through AI Apr 29, 2025 am 12:27 AM

AI can help optimize the use of Composer. Specific methods include: 1. Dependency management optimization: AI analyzes dependencies, recommends the best version combination, and reduces conflicts. 2. Automated code generation: AI generates composer.json files that conform to best practices. 3. Improve code quality: AI detects potential problems, provides optimization suggestions, and improves code quality. These methods are implemented through machine learning and natural language processing technologies to help developers improve efficiency and code quality.

How to uninstall MySQL and clean residual files How to uninstall MySQL and clean residual files Apr 29, 2025 pm 04:03 PM

To safely and thoroughly uninstall MySQL and clean all residual files, follow the following steps: 1. Stop MySQL service; 2. Uninstall MySQL packages; 3. Clean configuration files and data directories; 4. Verify that the uninstallation is thorough.

See all articles