Java之JDBC常见错误

环境:MySQL Server 8.0 + mysql-connector-java-8.0.12.jar

代码(错误):

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class DBUtil {

    public static final String URL = "jdbc:mysql://localhost:3306/JForum";
    public static final String USER = "root";
    public static final String PASSWORD = "123456";

    public static void main(String[] args) throws Exception {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
        Statement st = conn.createStatement();
        ResultSet rs = st.executeQuery("select username,user_id from jforum_users");
        while(rs.next()){
            System.out.println(rs.getString("username") + "年龄:" + rs.getInt("user_id"));
        }
    }
}

报错(一):

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.

解决方案:

修改代码:"jdbc:mysql://localhost:3306/JForum"——>"jdbc:mysql://localhost:3306/JForum?useSSL=false"

报错(二):

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:mysql://localhost:3306/JForum?useSSL=false"——>"jdbc:mysql://localhost:3306/JForum?useSSL=false&serverTimezone=GMT%2B8"

或修改MySQL:

代码(正确):

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class DBUtil {

    public static final String URL = "jdbc:mysql://localhost:3306/JForum?useSSL=false&serverTimezone=GMT%2B8";
    public static final String USER = "root";
    public static final String PASSWORD = "123456";

    public static void main(String[] args) throws Exception {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
        Statement st = conn.createStatement();
        ResultSet rs = st.executeQuery("select username,user_id from jforum_users");
        while(rs.next()){
            System.out.println("姓名:" + rs.getString("username") + " 年龄:" + rs.getInt("user_id"));
        }
    }
}

猜你喜欢

转载自blog.csdn.net/WZ18810463869/article/details/82287919