IDEA spring项目使用jdbc连接数据库失败2019-05-11

报错如下:

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server.

原因是jdbc连接数据库时的驱动版本过低。

需要在配置文件(**.iml)中将mysql-connector-java的版本从5.1改为要连接的MySQL的版本(例如8.0.15)

mysql

mysql-connector-java

8.0.15

更改之后再次运行,报错:

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.Exception in thread "main" java.sql.SQLException: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.

这是一个MySQL的时区错误问题,需要将连接URL加上 serverTimezone=UTC 再次运行即可成功连接数据库。

//注册驱动

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

//获取数据

String url = "jdbc:mysql://localhost:3306/mysqldemo?serverTimezone=UTC";

Connection conn = DriverManager.getConnection(url,"root","password");

System.out.println(conn);

//获得语句执行平台

Statement stat = conn.createStatement();

System.out.println(stat);

//执行SQL语句int row = stat.executeUpdate("SELECT * FROM user");

System.out.println(row);

//处理结果

//释放资源

stat.close();

conn.close();

你可能感兴趣的:(IDEA spring项目使用jdbc连接数据库失败2019-05-11)