酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

用java写代码-- 10. 添加一个新的优惠券记录在表中 -- 11. 修改优惠券id=2的记录,将优惠券价格改成50,失效时间延后3天 -- 12. 删除tony 已过期且优惠价格<20元的优惠券记录

为了完成这些任务,你需要与数据库交互,并使用合适的SQL语句来执行这些操作。以下是一个简单的示例,假设你正在使用Java和JDBC来连接数据库(假设数据库为MySQL): 10. 添加一个新的优惠券记录在表中 ```java import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class CouponManager { // JDBC连接信息 private static final String URL = "jdbc:mysql://localhost:3306/your_database"; private static final String USER = "your_username"; private static final String PASSWORD = "your_password"; // 添加优惠券记录 public void addCoupon(String couponCode, double price, Date expiryDate) { String sql = "INSERT INTO coupons (coupon_code, price, expiry_date) VALUES (?, ?, ?)"; try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD); PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setString(1, couponCode); stmt.setDouble(2, price); stmt.setDate(3, new java.sql.Date(expiryDate.getTime())); int rowsInserted = stmt.executeUpdate(); if (rowsInserted > 0) { System.out.println("A new coupon was inserted successfully!"); } } catch (SQLException e) { e.printStackTrace(); } } } ``` 11. 修改优惠券id=2的记录,将优惠券价格改成50,失效时间延后3天 ```java public void updateCoupon(int couponId, double newPrice, Date newExpiryDate) { String sql = "UPDATE coupons SET price = ?, expiry_date = DATE_ADD(expiry_date, INTERVAL 3 DAY) WHERE id = ?"; try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD); PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setDouble(1, newPrice); stmt.setInt(2, couponId); int rowsUpdated = stmt.executeUpdate(); if (rowsUpdated > 0) { System.out.println("Coupon with ID " + couponId + " was updated successfully!"); } } catch (SQLException e) { e.printStackTrace(); } } ``` 12. 删除tony 已过期且优惠价格<20元的优惠券记录 ```java public void deleteExpiredCoupons(String username) { String sql = "DELETE FROM coupons WHERE username = ? AND expiry_date < CURRENT_DATE() AND price < 20"; try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD); PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setString(1, username); int rowsDeleted = stmt.executeUpdate(); System.out.println(rowsDeleted + " expired coupons deleted for user " + username); } catch (SQLException e) { e.printStackTrace(); } } ``` 请确保替换示例中的数据库连接信息(URL、USER、PASSWORD)以及表名和字段名,以便与你的实际数据库结构匹配。 [2024-06-29 15:28:49 | AI写代码神器 | 1943点数解答]

相关提问