国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Java > 正文

JDBC程序更新數(shù)據(jù)庫(kù)中記錄的方法

2019-11-26 14:54:37
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

本文實(shí)例講述了JDBC程序更新數(shù)據(jù)庫(kù)中記錄的方法。分享給大家供大家參考,具體如下:

使用JDBC程序(Eclipse、MyEclipse)更新數(shù)據(jù)庫(kù)(MySql)中的記錄時(shí)可以只修改記錄的一個(gè)字段或幾個(gè)字段,具體方法為可以加入如下被注釋代碼(前提是修改之前可以從數(shù)據(jù)庫(kù)中得到該條記錄)以u(píng)ser表為例

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; }}

調(diào)用:

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);}

希望本文所述對(duì)大家Java程序設(shè)計(jì)有所幫助。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 丽江市| 普格县| 永嘉县| 磐石市| 靖远县| 沧源| 永寿县| 朝阳市| 黔江区| 抚顺县| 陆川县| 长丰县| 扎鲁特旗| 怀集县| 芦溪县| 永胜县| 文登市| 泸西县| 黄梅县| 祁连县| 监利县| 行唐县| 临清市| 叶城县| 诸暨市| 方正县| 南京市| 崇义县| 安远县| 冀州市| 天津市| 珲春市| 高阳县| 隆安县| 沭阳县| 资阳市| 平罗县| 娱乐| 平罗县| 江达县| 织金县|