码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-08-17 17:29:01      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:修改   成功   code   release   exception   else   使用   void   except   

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完成添加,修改数据

标签:修改   成功   code   release   exception   else   使用   void   except   

原文地址:https://www.cnblogs.com/pxy-1999/p/13507191.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!