JDBC操作数据

    public void findStudent() {

        Connection conn = null;

        Statement stmt = null;

        ResultSet rs = null;

      try {

             //注册 mysql 驱动

        Class.forName("com.mysql.jdbc.Driver");

        //连接数据的基本信息 url ,username,password

        String url = "jdbc:mysql://localhost:3306/springdb"; String username = "root";

             //创建连接对象

         conn = DriverManager.getConnection(url, username, password);

        List<Student> stuList = new ArrayList<>();

        //创建 Statement, 用来执行 sql 语句

        stmt = conn.createStatement();

        //执行查询,创建记录集,

        rs = stmt.executeQuery("select * from student");

        while (rs.next()) {

                 Student stu = new Student();

                stu.setId(rs.getInt("id"));

     stu.setName(rs.getString("name"));

    stu.setAge(rs.getInt("age"));

          //从数据库取出数据转为 Student 对象,封装到 List 集合

             stuList.add(stu);

        }

    } catch (Exception e) { e.printStackTrace();

    } finally {

   try {

            //关闭资源

            if (rs != null) ;

    {

    stmt.close();
    rs.close();

    }

    if (conn != null) { conn.close();

           }

        } catch (Exception e) { e.printStackTrace();

                  }

             }

         }

posted @ 2021-02-04 14:11  8ling1ling  阅读(297)  评论(0)    收藏  举报