package chapter10;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.DriverManager;

public class Example01 {
    public static void main(String[] args) {
        try {
            // 1. 加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 2. 准备连接参数
            String url = "jdbc:mysql://localhost:3306/school?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC";
            String username = "root";
            String password = "root";

            // 使用try-with-resources自动关闭资源
            try (
                    // 创建连接
                    Connection connection = DriverManager.getConnection(url, username, password);
                    // 创建语句对象
                    Statement statement = connection.createStatement();
                    // 执行查询获取结果集
                    ResultSet resultSet = statement.executeQuery("select * from student")
            ) {
                // 处理结果集
                while (resultSet.next()) {
                    int id = resultSet.getInt("id");
                    String name = resultSet.getString("name");
                    int age = resultSet.getInt("age");
                    String gender = resultSet.getString("gender");
                    String className = resultSet.getString("class");

                    System.out.println("id=" + id + ", name=" + name + ", age=" + age +
                            ", gender=" + gender + ", className=" + className);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
