一个商店的商品进货记录表ProdPurchRcd的字段有进货单号PurchOrdNo、商品编码ProdCode、商品名ProdName、规格Spec、数量QTY、单价 Price、进货时间PurchTime,商品库存记录表ProdStorage的字段有商品编码ProdCode、商品名 ProdName、规格 Spee、单价Price、总数TQTY。每次进货,在ProdPurchRcd表中记录的同时,更新 ProdStorage表中的总数。完成以下要求: 试编写Java代码,实现(1)创建数据库ProdDB、创建ProdPurchRcd表和ProdStorage表。 (2)向 ProdPurchRcd表和ProdStorage表中添加记录。 (3)查询某商品的库存总数。
时间: 2023-06-20 12:09:45 浏览: 210
下面是实现上述需求的Java代码:
```
import java.sql.*;
public class ProductManagement {
private static final String DB_URL = "jdbc:mysql://localhost:3306/ProdDB";
private static final String USER = "root";
private static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
// 创建数据库ProdDB
String sql = "CREATE DATABASE IF NOT EXISTS ProdDB";
stmt.executeUpdate(sql);
// 创建ProdPurchRcd表
sql = "CREATE TABLE IF NOT EXISTS ProdPurchRcd " +
"(PurchOrdNo INT NOT NULL AUTO_INCREMENT, " +
" ProdCode VARCHAR(10) NOT NULL, " +
" ProdName VARCHAR(50) NOT NULL, " +
" Spec VARCHAR(50), " +
" QTY INT NOT NULL, " +
" Price DECIMAL(10,2) NOT NULL, " +
" PurchTime TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, " +
" PRIMARY KEY (PurchOrdNo))";
stmt.executeUpdate(sql);
// 创建ProdStorage表
sql = "CREATE TABLE IF NOT EXISTS ProdStorage " +
"(ProdCode VARCHAR(10) NOT NULL, " +
" ProdName VARCHAR(50) NOT NULL, " +
" Spec VARCHAR(50), " +
" Price DECIMAL(10,2) NOT NULL, " +
" TQTY INT NOT NULL, " +
" PRIMARY KEY (ProdCode))";
stmt.executeUpdate(sql);
// 向ProdPurchRcd表中添加记录
sql = "INSERT INTO ProdPurchRcd (ProdCode, ProdName, Spec, QTY, Price) " +
"VALUES ('001', '商品1', '规格1', 100, 10.00)";
stmt.executeUpdate(sql);
// 更新ProdStorage表中的总数
sql = "INSERT INTO ProdStorage (ProdCode, ProdName, Spec, Price, TQTY) " +
"VALUES ('001', '商品1', '规格1', 10.00, 100) " +
"ON DUPLICATE KEY UPDATE TQTY = TQTY + VALUES(TQTY)";
stmt.executeUpdate(sql);
// 查询某商品的库存总数
sql = "SELECT TQTY FROM ProdStorage WHERE ProdCode = '001'";
ResultSet rs = stmt.executeQuery(sql);
if (rs.next()) {
int totalQty = rs.getInt("TQTY");
System.out.println("商品001的库存总数为:" + totalQty);
}
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) stmt.close();
} catch (SQLException se2) {
}
try {
if (conn != null) conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
}
```
代码中使用了JDBC连接MySQL数据库,实现了创建ProdDB数据库、创建ProdPurchRcd和ProdStorage表,向表中添加记录,以及查询某商品的库存总数的功能。其中,向ProdPurchRcd表中添加记录使用了普通的INSERT语句,而更新ProdStorage表中的总数使用了ON DUPLICATE KEY UPDATE语句,可以避免重复插入记录。
阅读全文