【JDBC】学习路径6-SQL插入、修改、删除数据

Posted on 2022-05-23 17:39  罗芭Remoo  阅读(69)  评论(0编辑  收藏  举报

第一章:插入使用.executeUpdate();

返回的是受到影响的数据条数。

    public static boolean insert(String username,String password){
        Connection con=null;
        PreparedStatement pstmt =null;
        ResultSet rs =null;

        try {
            con = JDBCUtils.getConnection();

            String sql = "insert into user(username,password) values(?,?)";
            pstmt = con.prepareStatement(sql);
            pstmt.setString(1,username);
            pstmt.setString(2,password);
            int result = pstmt.executeUpdate();//返回印象的行数

            System.out.println("插入成功!");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            JDBCUtils.close(con,pstmt,rs);
        }
        return false;
    }

 

 

 


第二章:删除数据

传递id删除。

    public static boolean delete(int ID){
        Connection con=null;
        PreparedStatement pstmt =null;
        ResultSet rs =null;

        try {
            con = JDBCUtils.getConnection();

            String sql = "delete from user where id = ?";
            pstmt = con.prepareStatement(sql);
            pstmt.setInt(1,ID);
            int result = pstmt.executeUpdate();//返回印象的行数

            if(result>0)
                System.out.println("删除成功!");
            else
                System.out.println("删除失败!");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            JDBCUtils.close(con,pstmt,rs);
        }
        return false;
    }

第三章:修改数据

 

public static boolean update(int ID,String newPassword) {
    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;

    try {
        con = JDBCUtils.getConnection();

        String sql = "update user set password = ? where id = ?";
        pstmt = con.prepareStatement(sql);

        pstmt.setString(1, newPassword);
        pstmt.setInt(2, ID);

        int result = pstmt.executeUpdate();//返回影响的行数

        if (result > 0)
            System.out.println("修改成功!");
        else
            System.out.println("修改失败!");
        return true;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        JDBCUtils.close(con, pstmt, rs);
    }
    return false;
}

 测试:

main中调用:

update(213,"123456");