Java IDEA下用连接MySQL8.0

2019-10-11  本文已影响0人  JaosnZhao

1.先安装mysql 参考连接:Java Web开发——MySQL数据库的安装与配置 - ChaoYoung - 博客园

2.idea上的基本配置

注意 : 手动测试连接的时候需要注意 4 一定要配置,负责会连接失败

3.出现jdbc驱动找不到的情况的情况 (Exception in thread "main" java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver)

检查是否依赖了mysql-connector-java这个jar (特别注意改jar包的版本号)

在idear 依赖这个库 :Maven Repository: mysql » mysql-connector-java » 8.0.17z

在gradle文件下添加依赖

4.代码

public static void main(String[] args)throws SQLException, ClassNotFoundException {

Connection conn =null;

        Statement stmt =null;

        ResultSet rs =null;

        try {

// 加载驱动类

            Class.forName("com.mysql.cj.jdbc.Driver");

            long start =System.currentTimeMillis();

            // 建立连接

//            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/zxdfirst",

            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/zxdfirst?serverTimezone=GMT",

                    "root", "root");

            long end = System.currentTimeMillis();

            System.out.println(conn);

            System.out.println("建立连接耗时: " + (end - start) +"ms 毫秒");

            // 创建Statement对象

            stmt = conn.createStatement();

            // 执行SQL语句

            rs = stmt.executeQuery("select * from account");

            System.out.println("id\tusername\tpwd\t\tregTime");

            while (rs.next()) {

System.out.println("名字" + rs.getString("name"));

                System.out.println(rs.getInt(1));

//                System.out.println(rs.getInt(1) + "\t" + rs.getString(2)

//                        + "\t\t" + rs.getString(3) + "\t\t" + rs.getString(4));

            }

}catch (SQLException e) {

e.printStackTrace();

        }finally {

try {

if (rs !=null) {

rs.close();

                }

}catch (SQLException e) {

e.printStackTrace();

            }

try {

if (stmt !=null) {

stmt.close();

                }

}catch (SQLException e) {

e.printStackTrace();

            }

try {

if (conn !=null) {

conn.close();

                }

}catch (SQLException e) {

e.printStackTrace();

            }

}

}

5.运行成功

上一篇下一篇

猜你喜欢

热点阅读