The JDBC program updates the methods recorded in the database

  • 2020-04-01 04:16:11
  • OfStack

This article illustrates how a JDBC program can update records in a database. Share with you for your reference, as follows:

When using a JDBC program (Eclipse, MyEclipse) to update a record in a database (MySql), you can modify only one or more fields of the record by adding the following annotated code (provided that the record can be obtained from the database before modification) to the user table as an example


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);
  //First get the record
  User user = getUserById(u.getId());
  //Determines whether the field needs to be modified
  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(" Success to user Update in the table " + i + " records ");
 } 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;
 }
}

Call:


public static void main(String[] args) {
 UserDao ud = new UserDaoJdbcImpl();
 User user = new User();
 user.setId(9);
 user.setName(" The teacher ");//Only the name and birthday properties are modified
 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); Do not modify the money property
 ud.update(user);
}

I hope this article has been helpful to you in Java programming.


Related articles: