使用 Java JDBC 生成食堂窗口和入账记录数据

本文介绍如何使用 Java JDBC 代码创建食堂窗口和入账记录数据库表,并填充随机数据。包含创建表结构、添加外键、生成随机数据以及插入数据等操作。

1. 完成两个表的创建

// 创建窗口表
String createWindowTable = "CREATE TABLE window ("
        + "window_id INT PRIMARY KEY AUTO_INCREMENT,"
        + "window_name VARCHAR(100) NOT NULL,"
        + "catering_type INT NOT NULL,"
        + "phone_number VARCHAR(11) NOT NULL"
        + ")";

// 创建入账记录表
String createRecordTable = "CREATE TABLE record ("
        + "record_id INT PRIMARY KEY AUTO_INCREMENT,"
        + "entry_time TIMESTAMP NOT NULL,"
        + "entry_amount DECIMAL(10, 2) NOT NULL,"
        + "window_id INT NOT NULL,"
        + "FOREIGN KEY (window_id) REFERENCES window(window_id)"
        + ")";

2. 分析表关系,并添加外键字段,实现表关系

窗口表(window)和入账记录表(record)之间的关系是一对多关系,一个窗口可以对应多条入账记录。因此,在入账记录表中添加 window_id 字段作为外键,关联到窗口表的主键 window_id

3. 完成向窗口表填加50条记录

// 生成随机手机号
public String generatePhoneNumber() {
    String phoneNumber = "1";
    phoneNumber += (int) (Math.random() * 9) + 1; // 第二位不能是2
    for (int i = 0; i < 9; i++) {
        phoneNumber += (int) (Math.random() * 10);
    }
    return phoneNumber;
}

// 插入窗口记录
String insertWindowRecord = "INSERT INTO window (window_name, catering_type, phone_number) VALUES (?, ?, ?)";

try (Connection connection = DriverManager.getConnection(url, username, password);
     PreparedStatement statement = connection.prepareStatement(insertWindowRecord)) {
    for (int i = 0; i < 50; i++) {
        statement.setString(1, "窗口" + (i + 1));
        statement.setInt(2, (int) (Math.random() * 4) + 1);
        statement.setString(3, generatePhoneNumber());
        statement.executeUpdate();
    }
} catch (SQLException e) {
    e.printStackTrace();
}

4. 完成向记录表添加10000条记录

// 生成随机入账时间
public Timestamp generateEntryTime() {
    long startTimestamp = Timestamp.valueOf("2022-07-24 00:00:00").getTime();
    long endTimestamp = Timestamp.valueOf("2022-07-30 23:59:59").getTime();
    long randomTimestamp = startTimestamp + (long) (Math.random() * (endTimestamp - startTimestamp));
    return new Timestamp(randomTimestamp);
}

// 插入入账记录
String insertRecord = "INSERT INTO record (entry_time, entry_amount, window_id) VALUES (?, ?, ?)";

try (Connection connection = DriverManager.getConnection(url, username, password);
     PreparedStatement statement = connection.prepareStatement(insertRecord)) {
    for (int i = 0; i < 10000; i++) {
        statement.setTimestamp(1, generateEntryTime());
        statement.setDouble(2, Math.random() * 100 + 1);
        statement.setInt(3, (int) (Math.random() * 50) + 1);
        statement.executeUpdate();
    }
} catch (SQLException e) {
    e.printStackTrace();
}

说明:

  • 以上代码中的 urlusernamepassword 需要根据实际情况进行修改。
  • 代码中包含随机数生成、日期时间操作等,可以根据实际需要进行调整。
  • 该代码只是示例,可以根据实际情况进行扩展和完善。

原文地址: https://www.cveoy.top/t/topic/p6BA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录