在Java中,更新(Update)通常指的是對數據庫中的記錄進行修改。以下是一些Java更新數據庫記錄的最佳實踐案例:
String sql = "UPDATE users SET name = ?, age = ? WHERE id = ?";
try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
pstmt.setString(1, "New Name");
pstmt.setInt(2, 30);
pstmt.setInt(3, 1);
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
Connection conn = null;
try {
conn = dataSource.getConnection();
conn.setAutoCommit(false); // 開啟事務
// 更新操作
String sql = "UPDATE users SET balance = balance - ? WHERE id = ?";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setDouble(1, 100.0);
pstmt.setInt(2, 1);
pstmt.executeUpdate();
}
// 提交事務
conn.commit();
} catch (SQLException e) {
if (conn != null) {
try {
conn.rollback(); // 回滾事務
} catch (SQLException ex) {
ex.printStackTrace();
}
}
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
String sql = "UPDATE users SET balance = balance - ? WHERE id = ?";
try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
for (int i = 0; i < updates.size(); i++) {
pstmt.setDouble(1, updates.get(i).getAmount());
pstmt.setInt(2, updates.get(i).getUserId());
pstmt.addBatch();
}
pstmt.executeBatch(); // 執行批量更新
} catch (SQLException e) {
e.printStackTrace();
}
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
try {
User user = session.get(User.class, userId);
if (user != null) {
user.setBalance(user.getBalance() - amount);
session.update(user);
}
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
Logger logger = LoggerFactory.getLogger(YourClass.class);
logger.info("Updating user balance: userId={}, amount={}", userId, amount);
// 更新操作
// ...
logger.info("User balance updated successfully: userId={}", userId);
PreparedStatement
外,還可以考慮使用其他支持參數化查詢的方法或庫,如MyBatis。這些最佳實踐可以幫助你更安全、高效地執行數據庫更新操作。