public class MyTest {
    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            //1.加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获得连接
            String username = "root";
            String Pwd = "123456";
            String url = "jdbc:mysql://localhost:3306/test?serverTimezone=UTC";
            connection = DriverManager.getConnection(url,username,Pwd);
            //3 定义sql  创建状态通道(进行sql语句的发送)
            statement = connection.createStatement();
            resultSet = statement.executeQuery("select * from student");
            //4 取出结果集
            while (resultSet.next()){//判断是否有下一条数据
                //取出数据
                System.out.println("学号"+resultSet.getInt("stuId")+ "\t"+"姓名:"+resultSet.getString("stuname"));
            }
        } catch (SQLException | ClassNotFoundException throwables) {
            throwables.printStackTrace();
        }finally {
    try {
        if(resultSet != null){
            resultSet.close();
        }
        if (statement != null){
            statement.close();
        }
        if(connection != null){
            connection.close();
        }
    } catch (SQLException throwables) {
        throwables.printStackTrace();
    }
}
    }
}
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐