JDBC(3)-使用PreparedStatement接口实现增、删、改操作

1、PreparedStatement接口引入

  PreparedStatement是Statement的子接口,属于预处理操作,与直接使用Statement不同的是,PreparedStatement在操作时,

  是先在数据表中准备好了一条SQL语句,但是此SQL语句的具体内容暂时不设置,而是之后再进行设置。

  (以后开发一般使用PreparedStatement,不用Statement)

2、使用PreparedStatement接口实现添加数据操作

public class JDBCDemo5 {
    private static MysqlUtil dbUtil = new MysqlUtil();
    /**
     * 添加emp
     * @param emp
     * @return
     * @throws Exception
     */
    private static int addEmp(Emp emp) throws Exception{
        Connection conn = dbUtil.getConnection();
        String sql = "insert into emp2 values(null,?,?,?)";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        pstmt.setString(1, emp.getName());
        pstmt.setDouble(2, emp.getSalary());
        pstmt.setInt(3, emp.getAge());
        int result = pstmt.executeUpdate();
        dbUtil.close(pstmt, conn);
        return result;
        
    }

    public static void main(String[] args) throws Exception {
        Emp emp = new Emp("pengpeng",13000,27);
        int result = addEmp(emp);
        if(result==1){
            System.out.println("添加成功");
        }else{
            System.out.println("添加失败");
        }


    }

}

3、使用PreparedStatement接口实现更新数据操作

public class JDBCDemo6 {

    private static MysqlUtil dbUtil = new MysqlUtil();
    private static int updateEmp(Emp emp) throws Exception{
        Connection conn = dbUtil.getConnection();
        String sql = "update emp2 set name=?,salary=?,age=? where id=?";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        pstmt.setString(1, emp.getName());
        pstmt.setDouble(2, emp.getSalary());
        pstmt.setInt(3, emp.getAge());
        pstmt.setInt(4, emp.getId());
        int result = pstmt.executeUpdate();
        dbUtil.close(pstmt, conn);
        return result;
    }
    public static void main(String[] args) throws Exception {
        Emp emp = new Emp(4,"pengpeng",13000,27);
        int result = updateEmp(emp);
        if(result==1){
            System.out.println("update成功");
        }else{
            System.out.println("update失败");
        }

        
    }

}

4、使用PreparedStatement接口实现删除数据操作

public class JDBCDemo7 {
    private static MysqlUtil dbUtil = new MysqlUtil();
    private static int deleteEmp(int id) throws Exception{
        Connection conn = dbUtil.getConnection();
        String sql = "delete from emp2 where id=?";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        pstmt.setInt(1, id);
        int result = pstmt.executeUpdate();
        dbUtil.close(pstmt, conn);
        return result;
    }

    public static void main(String[] args) throws Exception{
        Emp emp = new Emp(4,"pengpeng",13000,27);
        int result = deleteEmp(4);
        if(result==1){
            System.out.println("delete成功");
        }else{
            System.out.println("delete失败");
        }

    }

}
原文地址:https://www.cnblogs.com/sylovezp/p/4203677.html