1. 程式人生 > 實用技巧 >JAVA連線MySQL資料庫的警告處理以及可能的錯誤

JAVA連線MySQL資料庫的警告處理以及可能的錯誤

JAVA連線MySQL資料庫的警告處理以及可能的錯誤

IDEA控制檯報出的紅色警告

Mon Dec 21 20:43:40 CST 2020 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.

翻譯:12月21日星期一20:43:40 CST 2020警告:不建議在沒有伺服器身份驗證的情況下建立SSL連線。根據MySQL5.5.45+、5.6.26+和5.7.6+的要求,如果不設定顯式選項,則預設必須建立SSL連線。為了符合不使用SSL的現有應用程式,verifyServerCertificate屬性設定為“false”。您需要通過設定useSSL=false顯式禁用SSL,或者設定useSSL=true並提供用於伺服器證書驗證的信任庫。

處理過程

​ 在介面Connection的資料庫名稱url後新增設定useSSL=true

  • 處理前

    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb1","root","097052sf");
    
  • 處理後

    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb1?useSSL=true","root","097052sf");
    

可能犯的錯誤

  • 資料庫使用者表的建立

    USE mydb1;
    CREATE TABLE users(
           id INT PRIMARY KEY AUTO_INCREMENT,
           username VARCHAR(20) UNIQUE NOT NULL,
           PASSWORD VARCHAR(20) NOT NULL,
           phone VARCHAR(11) NOT NULL
    )CHARSET=utf8;
    INSERT INTO users (username,PASSWORD,phone) VALUES ('張三','1234','12345678901');
    INSERT INTO users (username,PASSWORD,phone) VALUES('李四','123','01234567899');
    INSERT INTO users(username,PASSWORD,phone) VALUES ('zs','1','12345678901');
    
  • IDEA連線資料庫查詢時

    請輸入使用者名稱:
    zs
    請輸入密碼:
    1
    登陸成功!
    
    Process finished with exit code 0
    
    請輸入使用者名稱:
    張三
    請輸入密碼:
    1234
    使用者名稱或密碼錯誤!
    
    Process finished with exit code 0
    

    由此可見,當輸入使用者名稱使用英文字元的時候符合預期結果,使用中文字元的時候,不符合預期結果。

    究其原因,應該是程式碼中缺少字元編碼設定,在JAVA的Connection介面的資料庫名稱後面再加上和資料庫設定一樣的字元編碼characterEncoding=utf8

    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb1?useSSL=true&characterEncoding=utf8","root","097052sf");
    

    執行結果

    請輸入使用者名稱:
    張三
    請輸入密碼:
    1234
    登陸成功!
    
    Process finished with exit code 0