使用java连接MySQL

     //驱动名称(MySQL 8.0之前版本的驱动为:"com.mysql.jdbc.Driver")
    private static String Driver = "com.mysql.cj.jdbc.Driver";
    //连接地址:格式为:jdbc:mysql://localhost:端口号(默认为3306)/数据库名称
    private static String Url = "jdbc:mysql://localhost:3306/你创建的数据库名称";
    //用户名
    private static String User = "root";
    //用户密码:这里是自己电脑上MySQL数据库的密码
    private static String Password = "123456";

    public static void main(String[] args) {
        try {
            //1、加载驱动
            Class.forName(Driver);
            //判断是否加载成功
            System.out.print("加载驱动成功!");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.out.println("加载驱动失败!");
        }
        Connection con = null;
        try{
            //2、获取数据库连接
            con = DriverManager.getConnection(Url,User,Password);
            System.out.println("获取数据库连接成功!");
            System.out.println("进行数据库操作!");
            //执行sql语句
            Statement statement = con.createStatement();
            // 查询(tag是表名)
            ResultSet resultSet = statement.executeQuery("select * from `tag`");

            //打印结果集
            while (resultSet.next()){
                System.out.print(resultSet.getString("aid") + " ");
                System.out.print(resultSet.getString("name") + " ");
                System.out.print(resultSet.getString("user_aid") + " ");
                System.out.println();
            }
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("获取数据库连接失败!");
        }
        finally {
            try{
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
posted @ 2022-10-12 14:20  合起来的彳亍  阅读(290)  评论(0编辑  收藏  举报