JDBC程式更新資料庫中記錄的方法_java

來源:互聯網
上載者:User

本文執行個體講述了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程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.