java点餐系统带mysql
时间: 2023-08-04 14:36:01 浏览: 84
OrderMeal(2).zipjava点餐系统javaswing版本+mysql结合jdbc实现的点餐
好的,下面是一个简单的Java点餐系统的示例代码,使用MySQL数据库进行数据存储和管理。
首先,您需要安装MySQL数据库,并创建一个名为“restaurant”的数据库,里面包含两个表:一个是“menu”表,用于记录菜单信息;另一个是“orders”表,用于记录客户订单信息。下面是创建这两个表的SQL语句:
```sql
CREATE TABLE menu (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
price FLOAT NOT NULL
);
CREATE TABLE orders (
id INT PRIMARY KEY AUTO_INCREMENT,
customer VARCHAR(50) NOT NULL,
dish VARCHAR(50) NOT NULL,
price FLOAT NOT NULL
);
```
然后,您需要在Java程序中引入MySQL的JDBC驱动程序,以便连接和操作MySQL数据库。这里使用的是MySQL Connector/J驱动程序,您可以从官网下载并安装。
接下来,我们可以编写Java代码来实现点餐系统。以下是示例代码:
```java
import java.sql.*;
public class Restaurant {
private static final String DB_URL = "jdbc:mysql://localhost:3306/restaurant";
private static final String DB_USER = "root";
private static final String DB_PASSWORD = "password";
public static void main(String[] args) {
try {
Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
System.out.println("Connected to database");
// 显示菜单
displayMenu(conn);
// 接受并处理订单
processOrder(conn);
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
private static void displayMenu(Connection conn) throws SQLException {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM menu");
System.out.println("Menu:");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
float price = rs.getFloat("price");
System.out.printf("%d. %s - $%.2f\n", id, name, price);
}
rs.close();
stmt.close();
}
private static void processOrder(Connection conn) throws SQLException {
PreparedStatement stmt = conn.prepareStatement("INSERT INTO orders (customer, dish, price) VALUES (?, ?, ?)");
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter your name: ");
String customer = scanner.nextLine();
while (true) {
System.out.print("Please enter the dish id (or 0 to finish): ");
int dishId = scanner.nextInt();
if (dishId == 0) {
break;
}
// 查询菜单并获取价格
PreparedStatement ps = conn.prepareStatement("SELECT price FROM menu WHERE id = ?");
ps.setInt(1, dishId);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
float price = rs.getFloat("price");
// 添加订单
stmt.setString(1, customer);
stmt.setInt(2, dishId);
stmt.setFloat(3, price);
stmt.executeUpdate();
System.out.printf("Added %d to your order - $%.2f\n", dishId, price);
} else {
System.out.println("Invalid dish id!");
}
rs.close();
ps.close();
}
stmt.close();
scanner.close();
}
}
```
这个Java程序首先连接到MySQL数据库,然后从“menu”表中获取菜单信息并显示出来。接着,它会提示用户输入姓名以及菜品编号,然后将订单信息插入到“orders”表中。用户可以输入多个菜品编号,直到输入0结束点餐。
请注意,上面的示例代码仅供参考,您需要根据自己的实际情况进行修改和调整。
阅读全文