MySQL5.0驱动与8.0驱动连接8.0服务器的出现的异常

JDBC连接MySQL8.0服务器异常

  • 5.0驱动连接
  • 8.0驱动连接

5.0驱动连接

java.sql.SQLException: Unknown initial character set index ‘255’ received from server. Initial client character set can be forced via the ‘characterEncoding’ property.
客户机与服务器字符集不同。
可在url最后加上?characterEncoding=utf8。

正确连接代码:

	//5.0
  	@Test
    public void testConnection1() throws IllegalAccessException, InstantiationException, ClassNotFoundException, SQLException {
        //1.提供另外三个连接的基本信息
        String url = "jdbc:mysql://localhost:3306/test?characterEncoding=utf8";
        String user = "root";
        String password = "root123";

        //2.加载Driver
        Class.forName("com.mysql.jdbc.Driver");//此步骤在连接MySQL时可以省

        //3.获取连接
        Connection connection = DriverManager.getConnection(url, user, password);
        System.out.println(connection);
    }   

8.0驱动连接

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.
需要配置时区:
在url后加?serverTimezone=UTC

我的服务器和驱动都是8.0版本的没有出现SSL的异常。应该是在服务器版本高于驱动版本时必须得指明SSL连接。
指明是否需要进行SSL连接
在url后加:
?useSSL=false

?useSSL=true

8.0获取驱动的位置也不同:
5.0时在:com.mysql.jdbc.Driver
8.0时在:com.mysql.cj.jdbc.Driver

正确连接代码:

	//8.0驱动
  	@Test
    public void testConnection2() throws IllegalAccessException, InstantiationException, ClassNotFoundException, SQLException {
        //1.提供另外三个连接的基本信息
        /*
        useSSL:MySQL在高版本需要指明是否进行SSL连接。版本相同就不必指明比如:
        String url = "jdbc:mysql://localhost:3306/test?serverTimezone=UTC";//此代码我运行也不报错
        serverTimezone:配置时区属性
        */
        String url = "jdbc:mysql://localhost:3306/test?&useSSL=false&serverTimezone=UTC";
        String user = "root";
        String password = "root123";

        //2.加载Driver
        Class.forName("com.mysql.cj.jdbc.Driver");

        //3.获取连接
        Connection connection = DriverManager.getConnection(url, user, password);
        System.out.println(connection);
    }   

你可能感兴趣的:(mysql,jdbc,数据库,java)