zoukankan      html  css  js  c++  java
  • JDBC 05: 插入,修改和删除数据

    1.  插入一个新用户

    public static void insert(String username,String password) {
    
            Connection con = null;
            PreparedStatement stmt = null;
            ResultSet rs = null;
            
            try {
                con = JDBCUtils.getConnection();
                
                String sql = "insert into user(username,password) values(?,?)";
                stmt = con.prepareStatement(sql);
                stmt.setString(1, username);
                stmt.setString(2, password);
                int result = stmt.executeUpdate(); // 返回值代表收到影响的行数
                
            } catch (Exception e) {
                
                e.printStackTrace();
            } finally {
                JDBCUtils.close(rs, stmt, con);
            }
        }

    2.  修改用户的密码

    public static void update(int id,String newPassword) {
    
            Connection con = null;
            PreparedStatement stmt = null;
            ResultSet rs = null;
            
            try {
                con = JDBCUtils.getConnection();
                
                String sql = "update user set password = ? where id = ?";
                stmt = con.prepareStatement(sql);
                stmt.setString(1, newPassword);
                stmt.setInt(2,id);
            
                int result = stmt.executeUpdate(); 
                if(result > 0) {
                    System.out.println("修改成功");
                }else {
                    System.out.println("修改失败");
                }
                
            } catch (Exception e) {        
                e.printStackTrace();
            } finally {
                JDBCUtils.close(rs, stmt, con);
            }
        }

    3.  删除用户

    public static void delete(int id) {
    
            Connection con = null;
            PreparedStatement stmt = null;
            ResultSet rs = null;
            
            try {
                con = JDBCUtils.getConnection();
                
                String sql = "delete from user where id=?";
                stmt = con.prepareStatement(sql);
                stmt.setInt(1, id);
            
                int result = stmt.executeUpdate(); 
                if(result > 0) {
                    System.out.println("删除成功");
                }else {
                    System.out.println("删除失败");
                }
                
            } catch (Exception e) {
                
                e.printStackTrace();
            } finally {
                JDBCUtils.close(rs, stmt, con);
            }
        }
  • 相关阅读:
    《剩女郎》的艺术魅力
    话剧《剩女郎》
    实验四
    手机app
    APP
    卡尔曼滤波 —— MATLAB实现
    卡尔曼滤波
    卡尔曼滤波
    2017 年全国大学生电子设计竞赛试题——四旋翼自主飞行器探测跟踪系统(C 题)【本科组】2
    2017 年全国大学生电子设计竞赛试题——四旋翼自主飞行器探测跟踪系统(C 题)【本科组】2
  • 原文地址:https://www.cnblogs.com/JasperZhao/p/13544002.html
Copyright © 2011-2022 走看看