Could not create connection to database server.亲测有效

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server.
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.Util.getInstance(Util.java:386)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1015)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:975)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:920)
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2565)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2301)
    at com.mysql.jdbc.ConnectionImpl.(ConnectionImpl.java:834)
    at com.mysql.jdbc.JDBC4Connection.(JDBC4Connection.java:47)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:416)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:346)
    at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:677)
    at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
    at testCon.main(testCon.java:25)

 

解决办法,jdbc与sql服务器版本不同,需匹配一致,mysql是8.x的话,jdbc换成mysql-connector-java-8.x版本

并且驱动:Class.forName("com.mysql.jdbc.Driver");

改成:Class.forName("com.mysql.cj.jdbc.Driver");

最后还可能出现

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.

那么连接获取的url由:jdbc:mysql://localhost:3306/db1

改成:jdbc:mysql://localhost:3306/db1?serverTimezone=GMT%2B8

jdbc8百度网盘链接:链接:https://pan.baidu.com/s/1f1NTYGZ_hIQ8XU4f41gNpw 
提取码:qw2s

你可能感兴趣的:(Could not create connection to database server.亲测有效)