当前位置: 移动技术网 > IT编程>开发语言>Java > JDBC程序更新数据库中记录的方法

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

2019年07月22日  | 移动技术网IT编程  | 我要评论

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

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

public class userdaojdbcimpl implements userdao {
 public void update(user u) {
 connection conn = null;
 preparedstatement ps = null;
 resultset rs = null;
 try {
  conn = jdbcutils.getconnection();
  string sql = "update user set name = ?, birthday = ?, money = ? where id=?";
  ps = conn.preparestatement(sql);
  // 首先得到该记录
  user user = getuserbyid(u.getid());
  // 判断字段是否需要修改
  if (u.getname() == null) {
  u.setname(user.getname());
  }
  if (u.getbirthday() == null) {
  u.setbirthday(user.getbirthday());
  }
  if (u.getmoney() == 0) {
  u.setmoney(user.getmoney());
  }
  ps.setstring(1, u.getname());
  ps.setdate(2, new java.sql.date(u.getbirthday().gettime()));
  ps.setdouble(3, u.getmoney());
  ps.setint(4, u.getid());
  int i = ps.executeupdate();
  system.out.println("成功向user表中更新" + i + "条记录");
 } catch (sqlexception e) {
  e.printstacktrace();
 } finally {
  jdbcutils.free(rs, ps, conn);
 }
 }
 public user getuserbyid(int id) {
 connection conn = null;
 preparedstatement ps = null;
 resultset rs = null;
 user user = null;
 try {
  conn = jdbcutils.getconnection();
  string sql = "select * from user where id = ?";
  ps = conn.preparestatement(sql);
  ps.setint(1, id);
  rs = ps.executequery();
  if (rs.next()) {
  user = new user();
  user.setid(rs.getint("id"));
  user.setname(rs.getstring("name"));
  user.setbirthday(rs.getdate("birthday"));
  user.setmoney(rs.getdouble("money"));
  }
 } catch (sqlexception e) {
  e.printstacktrace();
 } finally {
  jdbcutils.free(rs, ps, conn);
 }
 return user;
 }
}

调用:

public static void main(string[] args) {
 userdao ud = new userdaojdbcimpl();
 user user = new user();
 user.setid(9);
 user.setname("老师");//只修改name和birthday属性
 date d = null;
 try {
  simpledateformat sdf = new simpledateformat("yyyy-mm-dd");
  d = sdf.parse("1999-9-14");
 } catch (parseexception e) {
  e.printstacktrace();
 }
 user.setbirthday(d);
 //user.setmoney(1234);不修改money属性
 ud.update(user);
}

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网