Could not get JDBC Connection
错误信息为:
Exception in thread “main” org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server.
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:80)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:394)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:443)
at com.itheima.jdbc.JdbcTemplateTest.main(JdbcTemplateTest.java:14)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server.
newFile.xml配置正确情况下 可能由于数据库驱动包jar版本过低
我用的是mysql-connector-java-5.1.28.jar
改为mysql-connector-java-8.0.9-rc.jar
mysql-connector-java-8.0.9-rc.jar链接
提取码:ppsl
使用后可能报以下错误
WARN: Establishing SSL connection without server’s identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn’t set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to ‘false’. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Exception in thread “main” org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get 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.
原因:
从JDBC6.0开始驱动类使用了新的Driver,并且url中必须要设置时区,否则会报错
value="jdbc:mysql://localhost/spring?serverTimezone=UTC"></property>
并使用新的Driver
<property name="driverClassName"
value="com.mysql.cj.jdbc.Driver"></property>
附上jdbc配置文件模板
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
<!-- 1.配置数据源 -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- 1.1.数据库驱动 -->
<property name="driverClassName"
value="com.mysql.cj.jdbc.Driver"></property>
<!-- 1.2.连接数据库的url -->
<property name="url"
value="jdbc:mysql://localhost/spring?serverTimezone=UTC"></property>
<!-- 1.3.连接数据库的用户名 -->
<property name="username" value="root"></property>
<!-- 1.4.连接数据库的密码 -->
<property name="password" value="123"></property>
</bean>
<!-- 2配置JDBC模板 -->
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<!-- 默认必须使用数据源 -->
<property name="dataSource" ref="dataSource"/>
</bean>