Java JDBC 連接 MySQL8 數據庫


MySQL 8.0 以上版本的數據庫連接有所不同:

  • 1、MySQL 8.0 以上版本驅動包版本 mysql-connector-java-8.0.16.jar。

  • 2、com.mysql.jdbc.Driver 更換為 com.mysql.cj.jdbc.Driver

  • MySQL 8.0 以上版本不需要建立 SSL 連接的,需要顯示關閉。

  • allowPublicKeyRetrieval=true 允許客戶端從服務器獲取公鑰。

  • 最后還需要設置 CST。

加載驅動與連接數據庫方式如下:

Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test_demo?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC","root","password");
package com.runoob.test;
 
import java.sql.*;

//java項目www.fhadmin.org
public class MySQLDemo {
 
    // MySQL 8.0 以下版本 - JDBC 驅動名及數據庫 URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
    static final String DB_URL = "jdbc:mysql://localhost:3306/RUNOOB";
 
    // MySQL 8.0 以上版本 - JDBC 驅動名及數據庫 URL
    //static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";  
    //static final String DB_URL = "jdbc:mysql://localhost:3306/RUNOOB?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
 
 
    // 數據庫的用戶名與密碼,需要根據自己的設置
    static final String USER = "root";
    static final String PASS = "123456";
 
    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        try{
            // 注冊 JDBC 驅動
            Class.forName(JDBC_DRIVER);
        
            // 打開鏈接
            System.out.println("連接數據庫...");
            conn = DriverManager.getConnection(DB_URL,USER,PASS);
        
            // 執行查詢
            System.out.println(" 實例化Statement對象...");
            stmt = conn.createStatement();
            String sql;
            sql = "SELECT id, name, url FROM websites";
            ResultSet rs = stmt.executeQuery(sql);
        
            // 展開結果集數據庫
            while(rs.next()){
                // 通過字段檢索
                int id  = rs.getInt("id");
                String name = rs.getString("name");
                String url = rs.getString("url");
    
                // 輸出數據
                System.out.print("ID: " + id);
                System.out.print(", 站點名稱: " + name);
                System.out.print(", 站點 URL: " + url);
                System.out.print("\n");
            }
            // 完成后關閉
            rs.close();
            stmt.close();
            conn.close();
        }catch(SQLException se){
            // 處理 JDBC 錯誤
            se.printStackTrace();
        }catch(Exception e){
            // 處理 Class.forName 錯誤
            e.printStackTrace();
        }finally{
            // 關閉資源
            try{
                if(stmt!=null) stmt.close();
            }catch(SQLException se2){
            }// 什么都不做
            try{
                if(conn!=null) conn.close();
            }catch(SQLException se){
                se.printStackTrace();
            }
        }
        System.out.println("Goodbye!");
    }
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM