欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

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

时间:2020-12-06 09:42:44|栏目:JAVA代码|点击:

本文实例讲述了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程序设计有所帮助。

上一篇:Centos7.3下jre1.8安装和配置教程

栏    目:JAVA代码

下一篇:springboot集成mybatisplus实例详解

本文标题:JDBC程序更新数据库中记录的方法

本文地址:http://www.codeinn.net/misctech/29989.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有