酷代码 AI
菜单
服务商
DeepSeek字节豆包讯飞星火
更多选项

Java 与 SQL 联手:打造花店购物系统详细代码示例

以下是一个简单的花店购物系统的示例代码,包含了商品类、订单类、数据库操作等部分,代码中使用了 MySQL 数据库。 ```java import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; // 商品类 class FlowerProduct { private int id; private String name; private double price; public FlowerProduct(int id, String name, double price) { this.id = id; this.name = name; this.price = price; } public int getId() { return id; } public String getName() { return name; } public double getPrice() { return price; } } // 订单类 class FlowerOrder { private int orderId; private int productId; private int quantity; public FlowerOrder(int orderId, int productId, int quantity) { this.orderId = orderId; this.productId = productId; this.quantity = quantity; } public int getOrderId() { return orderId; } public int getProductId() { return productId; } public int getQuantity() { return quantity; } } public class FlowerShopSystem { // 数据库连接参数 private static final String DB_URL = "jdbc:mysql://localhost:3306/flower_shop"; private static final String USER = "root"; private static final String PASS = "your_password"; // 获取商品列表 public List<FlowerProduct> getProducts() { List<FlowerProduct> products = new ArrayList<>(); try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM products"); ResultSet rs = stmt.executeQuery()) { while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); double price = rs.getDouble("price"); products.add(new FlowerProduct(id, name, price)); } } catch (SQLException e) { e.printStackTrace(); } return products; } // 创建订单 public void createOrder(FlowerOrder order) { try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); PreparedStatement stmt = conn.prepareStatement("INSERT INTO orders (product_id, quantity) VALUES (?,?)")) { stmt.setInt(1, order.getProductId()); stmt.setInt(2, order.getQuantity()); stmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } // 主函数 public static void main(String[] args) { FlowerShopSystem system = new FlowerShopSystem(); // 获取商品列表并打印 List<FlowerProduct> products = system.getProducts(); for (FlowerProduct product : products) { System.out.println(product.getId() + " - " + product.getName() + " - $" + product.getPrice()); } // 创建订单示例 FlowerOrder order = new FlowerOrder(1, 1, 5); system.createOrder(order); } } ``` 注意点: 1. 请确保数据库已正确创建和配置,包括表结构和用户权限。 2. 在实际应用中,需要添加更多的错误处理和边界情况的处理。 3. 代码中的数据库连接参数需要根据实际情况进行修改。 ######[AI写代码神器 | 847点数解答 | 2025-03-06 19:10:15]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]