当前位置:首页 > Java API 与类库手册 > 正文

Java优学网MySQL函数教程:高效处理数据与避免精度丢失的实用指南

SELECT UPPER(username) FROM users WHERE LENGTH(username) > 5;

public String formatName(String name) {

if (name == null || name.isEmpty()) return name;
return name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase();

}

Map<String, BigDecimal> departmentSales = new HashMap<>(); for (SaleRecord record : saleRecords) {

String key = record.getDepartment() + "_" + record.getMonth();
BigDecimal current = departmentSales.getOrDefault(key, BigDecimal.ZERO);
departmentSales.put(key, current.add(record.getAmount()));

}

// 错误示例 PreparedStatement stmt = conn.prepareStatement("SELECT price FROM products WHERE id = ?"); stmt.setInt(1, productId); ResultSet rs = stmt.executeQuery(); if (rs.next()) {

double price = rs.getDouble("price"); // 可能丢失精度

}

// 正确做法 BigDecimal price = rs.getBigDecimal("price");

// 纯Java计算方式 public BigDecimal calculateOrderTotal(List items, String couponCode) {

BigDecimal subtotal = items.stream()
    .map(item -> item.getPrice().multiply(BigDecimal.valueOf(item.getQuantity())))
    .reduce(BigDecimal.ZERO, BigDecimal::add);

BigDecimal discount = calculateCouponDiscount(subtotal, couponCode);
BigDecimal tax = subtotal.multiply(TAX_RATE);

return subtotal.subtract(discount).add(tax);

}

Java优学网MySQL函数教程:高效处理数据与避免精度丢失的实用指南

Java优学网MySQL函数教程:高效处理数据与避免精度丢失的实用指南

你可能想看:

相关文章:

文章已关闭评论!