首页 > 技术文章 > 使用JDBC连接MySql时出现的几个问题

cheng- 2020-08-30 20:01 原文

使用JDBC连接MySql时出现

问题一:

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.

com.mysql.jdbc.Driver改为com.mysql.cj.jdbc.Driver

原因:当使用驱动mysql-connector-java 5时,JDBC连接MySQL应使用com.mysql.jdbc.Driver 。
当使用驱动mysql-connector-java 6及以上版本时,JDBC连接MySQL应使用com.mysql.cj.jdbc.Driver ,同时,还需要指定时区serverTimezone(解决方法如下)

问题二:

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.

在连接字符串后面加上?serverTimezone=UTC
其中UTC是统一标准世界时间。
解决中文乱码输入问题:?useUnicode=true&characterEncoding=UTF-8

完整的连接字符串示例:
jdbc:mysql://127.0.0.1:3306/(数据库名称)?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
或者:
jdbc:mysql://localhost:3306/(数据库名称)?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC

问题三:

如图

在Maven项目中连接MySQL数据库时NullPointerException

原因: .properties文件在maven项目中不能加载

解决方法:在maven项目中,配置文件一定要放到resources中,在默认情况下,不加载/src项目下的配置文件

推荐阅读