使用PreparedStatement完成添加,修改数据

public class JDBCDemo03 {
    //添加一条数据
    @Test
    public void addOne() throws SQLException {
        //1.获取连接
        Connection con = JDBCUtil.getConnect();

        //2.定义sql语句,参数?代替
        String sql = "insert into users(uid,uname,upass) values(?,?,?)";

        //3.获取执行sql语句的PreparedStatement对象
        PreparedStatement pstmt = con.prepareStatement(sql);

        //4.调用方法赋值
        pstmt.setObject(1,"u005");
        pstmt.setObject(2,"baoqiang");
        pstmt.setObject(3,"baoqiang");
        //5.执行增加操作
        int result = pstmt.executeUpdate();
        //6.处理结果
        if (result >0){
            System.out.println("添加一条记录成功");
        }else {
            System.out.println("添加一条记录失败");
        }
        //7.释放资源
        JDBCUtil.release(con,pstmt,null);
    }
    //修改一条数据
    @Test
    public void updateOne() throws SQLException {
        Connection con = JDBCUtil.getConnect();

        String sql = "update users set upass=? where uid=?";
        PreparedStatement pstmt = con.prepareStatement(sql);
        pstmt.setString(1,"qiangbao");
        pstmt.setString(2,"u005");
        int res = pstmt.executeUpdate();
        if (res >0){
            System.out.println("修改一条记录成功");
        }else {
            System.out.println("修改一条记录失败");
        }
        JDBCUtil.release(con,pstmt,null);
    }
}

 

你可能感兴趣的:(使用PreparedStatement完成添加,修改数据)