在学习spring JdbcTemplate的过程中,我已经按照书上的内容设置好了dataSource数据源和JDBC模板,测试程序在运行时却出现了两个问题。具体问题和解决方案如下:
Loading class “com.mysql.jdbc.Driver”. This is deprecated
控制台输出如下:
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”。 通过SPI自动注册驱动程序,通常不需要手动加载驱动程序类
关于第一个问题,经过网上寻找答案,了解到当使用驱动mysql-connector-java 5
时,JDBC连接MySQL应使用com.mysql.jdbc.Driver
。
当使用驱动mysql-connector-java 6
及以上版本时,JDBC连接MySQL应使用com.mysql.cj.jdbc.Driver
,同时,还需要指定时区serverTimezone
(见问题二)。
其实,在新版的MySQL驱动中,我们并不需要自己书写加载驱动程序的代码,只书写url和用户名密码的代码,也可以实现连接。
代码如下:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!--<property name="driverClassName" value="com.mysql.jdbc.Driver" />-->
<!--连接数据库的url-->
<property name="url" value="jdbc:mysql://localhost/spring?serverTimezone=Asia/Shanghai" />
<property name="username" value="root" />
<property name="password" value="123456" />
</bean>
The server time zone value ‘�й���ʱ��’ is unrecognized
控制台输出如下:
Exception in thread “main” org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is 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.
翻译过来就是
无法获取JDBC连接; 嵌套的异常为java.sql.SQLException:服务器时区值“”。无法识别或表示多个时区。 如果要利用时区支持,则必须配置服务器或JDBC驱动程序(通过“ serverTimezone”配置属性)以使用更特定的时区值。
关于第二个问题,这是因为我们没有指定MySQL的时区。
我们可以在url中添加代码?serverTimezone=UTC
解决此问题,但是如果设定serverTimezone=UTC
,会比中国时间早8个小时,如果在中国,可以选择Asia/Shanghai
或者Asia/Hongkong
,代码如下:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!--<property name="driverClassName" value="com.mysql.jdbc.Driver" />-->
<!--连接数据库的url-->
<property name="url" value="jdbc:mysql://localhost/spring?serverTimezone=Asia/Shanghai" />
<property name="username" value="root" />
<property name="password" value="123456" />
</bean>