JDBC增删

一.JDBC操作数据库的步骤

1.首先在项目根目录创建lib文件夹,放入jdbc驱动程序,然后Add As Library

2.加载数据库驱动

3.使用驱动管理器来获得连接---获得 一个数据库连接对象Connectiion

4.使用Connection创建PreparedStatement语句对象---PreparedStatement对象可以执行sql语句

5.使用PreparedStatement对象执行sql语句

6.操作判断---增删改返回的是影响行数,只有查询获得结果


 

 @Test
    public void testSelectAll() throws ClassNotFoundException, SQLException {
        //1.加载数据库驱动
        Class.forName(driver);
        //2.使用驱动管理器来获得链接---获得一个数据库连接对象Connection
        Connection con = DriverManager.getConnection(url, username, password);
        //3.使用Connection创建PreparedStatement预处理对象---PreparedStatement对象可以
        //执行带 ? 的sql语句
        String sql="select * from student";
        PreparedStatement ps = con.prepareStatement(sql);
        //4.使用PreparedStatement对象执行SQL语句,获得ResultSet结果集对象
        ResultSet rs = ps.executeQuery();
        //5.操作判断--增删改返回的是影响的行数(返回值是int),只有查询获得结果集(返回值
        //ResultSet)
        List<Student> studentList=new ArrayList<>();
        while(rs.next()){
            //更具字段名城获取表中的数据
            int stuId=rs.getInt("stuId");
            String stuName = rs.getString("stuName");
            String stuSex = rs.getString("stuSex");
            int stuAge = rs.getInt("stuAge");
            String stuAddr = rs.getString("stuAddr");
            //把以上数据封装到Student对象中
            Student student=new Student();
            student.setStuId(stuId);
            student.setStuName(stuName);
            student.setStuSex(stuSex);
            student.setStuAge(stuAge);
            student.setStuAddr(stuAddr);
            //把当前行封装后的student 对象装在到list集合中
            studentList.add(student);
        }
        System.out.println("studentList");
        //6.关闭资源
        if(rs!=null){
            rs.close();
        }
        if(ps!=null){
            ps.close();
        }
        if(con!=null){
            con.close();
        }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值