首页 > 开发 > Java > 正文

JDBC程序更新数据库中记录的方法

2024-07-13 09:55:52
字体:
来源:转载
供稿:网友

这篇文章主要介绍了JDBC程序更新数据库中记录的方法,涉及Java基于JDBC操作数据库的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下

本文实例讲述了JDBC程序更新数据库中记录的方法。分享给大家供大家参考,具体如下:

使用JDBC程序(Eclipse、MyEclipse)更新数据库(MySql)中的记录时可以只修改记录的一个字段或几个字段,具体方法为可以加入如下被注释代码(前提是修改之前可以从数据库中得到该条记录)以user表为例

 

 
  1. public class UserDaoJdbcImpl implements UserDao { 
  2. public void update(User u) { 
  3. Connection conn = null
  4. PreparedStatement ps = null
  5. ResultSet rs = null
  6. try { 
  7. conn = JdbcUtils.getConnection(); 
  8. String sql = "update user set name = ?, birthday = ?, money = ? where id=?"
  9. ps = conn.prepareStatement(sql); 
  10. // 首先得到该记录 
  11. User user = getUserById(u.getId()); 
  12. // 判断字段是否需要修改 
  13. if (u.getName() == null) { 
  14. u.setName(user.getName()); 
  15. if (u.getBirthday() == null) { 
  16. u.setBirthday(user.getBirthday()); 
  17. if (u.getMoney() == 0) { 
  18. u.setMoney(user.getMoney()); 
  19. ps.setString(1, u.getName()); 
  20. ps.setDate(2, new java.sql.Date(u.getBirthday().getTime())); 
  21. ps.setDouble(3, u.getMoney()); 
  22. ps.setInt(4, u.getId()); 
  23. int i = ps.executeUpdate(); 
  24. System.out.println("成功向user表中更新" + i + "条记录"); 
  25. catch (SQLException e) { 
  26. e.printStackTrace(); 
  27. finally { 
  28. JdbcUtils.free(rs, ps, conn); 
  29. public User getUserById(int id) { 
  30. Connection conn = null
  31. PreparedStatement ps = null
  32. ResultSet rs = null
  33. User user = null
  34. try { 
  35. conn = JdbcUtils.getConnection(); 
  36. String sql = "select * from user where id = ?"
  37. ps = conn.prepareStatement(sql); 
  38. ps.setInt(1, id); 
  39. rs = ps.executeQuery(); 
  40. if (rs.next()) { 
  41. user = new User(); 
  42. user.setId(rs.getInt("id")); 
  43. user.setName(rs.getString("name")); 
  44. user.setBirthday(rs.getDate("birthday")); 
  45. user.setMoney(rs.getDouble("money")); 
  46. catch (SQLException e) { 
  47. e.printStackTrace(); 
  48. finally { 
  49. JdbcUtils.free(rs, ps, conn); 
  50. return user; 

调用:

 

 
  1. public static void main(String[] args) { 
  2. UserDao ud = new UserDaoJdbcImpl(); 
  3. User user = new User(); 
  4. user.setId(9); 
  5. user.setName("老师");//只修改name和birthday属性 
  6. Date d = null
  7. try { 
  8. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 
  9. d = sdf.parse("1999-9-14"); 
  10. catch (ParseException e) { 
  11. e.printStackTrace(); 
  12. user.setBirthday(d); 
  13. //user.setMoney(1234);不修改money属性 
  14. ud.update(user); 

希望本文所述对大家Java程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表