在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。这些最佳实践可以帮助你更安全、高效地执行数据库更新操作。