/**
* 根据商品ID获取商品信息。
* Retrieve product information based on its ID.
*
* @param productId 商品ID
* @return 商品对象,如果未找到则返回 null。
* A product object, or null if the product is not found.
*/
public static Product getProductById(int productId) {
Product product = null; // 初始化商品对象
Connection connection = null; // 数据库连接
ResultSet resultSet = null; // 查询结果集
Statement statement = null; // SQL语句执行对象
try {
// 1. 建立数据库连接
connection = DB.getConnection();
// 2. 创建SQL查询语句
String sql = "SELECT c.id as cid, c.name as cname, p.id as pid, p.name as pname, price, image FROM category c JOIN product p ON c.id = p.categoryid WHERE p.id = " + productId;
// 3. 执行SQL查询
statement = connection.createStatement();
resultSet = statement.executeQuery(sql);
// 4. 遍历查询结果
if (resultSet.next()) {
// 4.1 创建分类对象并填充数据
Category category = new Category();
category.setId(resultSet.getInt("cid"));
category.setName(resultSet.getString("cname"));
// 4.2 创建商品对象并填充数据
product = new Product(); // 初始化商品对象
product.setId(resultSet.getInt("pid"));
product.setName(resultSet.getString("pname"));
product.setPrice(resultSet.getDouble("price"));
product.setImage(resultSet.getString("image"));
product.setCategory(category);
}
} catch (Exception e) {
Logger.getLogger(ProductService.class.getName()).severe("Error in getProductById: " + e.getMessage());
} finally {
// 5. 释放数据库资源
closeResources(resultSet, statement, connection);
}
return product;
}