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)

<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();

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。