关闭数据库连接资源Connection、Statement、ResultSet

编写代码关闭数据库连接资源,Connection、Statement、ResultSet

示例代码如下。

String url = "jdbc:mysql://127.0.0.1:3306/test";
        String username = "root";
        String password = "12345678";
        // 1. 获取连接
        Connection connection = DriverManager.getConnection(url, username, password);
        // 2. 获取查询语句
        PreparedStatement preparedStatement = connection.prepareStatement("select * from test");
        // 3. 执行查询,获取结果集
        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()){
            // 4. 从结果集取数据
            int id = resultSet.getInt("id");
            System.out.println(id);
        }
        // 5. 关闭连接
        resultSet.close();
        preparedStatement.close();
        connection.close();