JDBC连接mySQL数据库代码

@Test
    public void test1() {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
//      1、加载驱动Class.forName("");
            Class.forName("com.mysql.cj.jdbc.Driver");
//      2、获得连接对象Connection
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/study?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2b8", "root", "123456");
//      3、写sql语句
            String sql = "select id,name,age,gender from student";
//      4、创建Statement(一艘船)
            statement = connection.createStatement();
//      5、执行sql语句
//      (1) 更新类(更改了表里面数据):delete/update/insert      executeUpdate()
//      返回值:int,表示你影响的行数
//      (2)查询(没有改变表里面数据):  select                              executeQuery()
//      返回值:结果集ResultSet
            resultSet = statement.executeQuery(sql);
            List<Student> list = new ArrayList<>();
            while(resultSet.next()) {//判断下一个有没有,如果没有返回false,如果有返回true,并且指向这一行
                //当前resultSet指向第一行
                //while循环每遍历一次,把这一行每个字段的值拿出来
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                int age = resultSet.getInt("age");
                String gender = resultSet.getString("gender");
                Student student = new Student(id,name,age,gender);
                list.add(student);
            }
            for (Student student : list) {
                System.out.println(student);
            }

        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
//      6、关闭连接
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值