美文网首页
IDEA spring项目使用jdbc连接数据库失败2019-0

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

作者: yogoshary | 来源:发表于2019-05-11 16:15 被阅读0次

报错如下:

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

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

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

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<version>8.0.15</version>

</dependency>

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

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-0

      本文链接:https://www.haomeiwen.com/subject/lrgxaqtx.html