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 驱动名及数据库 URLstatic 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 www.sangpi.comsql; 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!");}
}