Eclipse連接配接MySQL資料庫 — 8.0版jdbc驅動
工具
mysql-connector-java-8.0.11.jar
eclipse
mysql-8.0.11
01. jdbc 8.0.11下載下傳
下載下傳網址:https://dev.mysql.com/downloads/connector/j/
下載下傳後解壓即可。
02. eclipse加載jdbc
打開eclipse,建立一個【java項目-MySQLTest】
點選MySQLTest右鍵,【建構路徑】 —> 【添加庫】—> 【使用者庫】—> 【使用者庫(u)…】—> 【建立一個使用者庫mysqllib】—> 選中建立的使用者庫,點選【添加外部JAR(x)…】,選擇解壓檔案中的【mysql-connector-java-8.0.11.jar】—> 【确定—>完成】。
03. java連接配接資料庫讀取資料
在Navicat Premium中建一張資料表
資料庫名【test】
表名【grade】
java連接配接資料庫代碼:
package mysql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class connect {
public static void main(String[] args){
// 加載資料庫驅動 com.mysql.jdbc.Driver
String driver = "com.mysql.cj.jdbc.Driver";
// 擷取mysql連接配接位址
String url = "jdbc:mysql://localhost:3306/test?&useSSL=false&serverTimezone=UTC";
// 資料名稱
String username = "root";
// 資料庫密碼
String password = "1025";
// 擷取一個資料的連接配接
Connection conn = null;
// 擷取連接配接的一個狀态
try{
Class.forName(driver);
//getConnection()方法,連接配接MySQL資料庫!
conn=DriverManager.getConnection(url,username,password);
if(!conn.isClosed())
System.out.println("資料庫連接配接成功!");
//建立statement類對象,用來執行SQL語句!
Statement Statement=conn.createStatement();
//要執行的SQL語句
String sql="select * from grade" ;
//ResultSet類,用來存放擷取的結果集!
ResultSet rs=Statement.executeQuery(sql);
System.out.println("-------------------------------");
System.out.println("執行結果如下所示:");
System.out.println("-------------------------------");
System.out.println("學号" + "\t" + "姓名"+"\t"+"數學成績"+"\t"+"國文成績");
System.out.println("-------------------------------");
String id=null;
String name=null;
String math=null;
String chinese=null;
while(rs.next()){
//擷取‘學号’這列資料
id=rs.getString("學号");
//擷取‘姓名’這列資料
name=rs.getString("姓名");
//擷取‘數學成績’這列資料
math=rs.getString("數學成績");
//擷取‘國文成績’這列資料
chinese=rs.getString("國文成績");
//輸出結果
System.out.println(id+"\t"+name+"\t"+math+"\t"+chinese);
}
rs.close();
conn.close();
}
catch(ClassNotFoundException e){
//資料庫驅動類異常處理
System.out.println("資料庫驅動加載失敗!");
e.printStackTrace();
}
catch(SQLException e1){
//資料庫連接配接失敗異常處理
e1.printStackTrace();
}
catch(Exception e2){
e2.printStackTrace();
}
finally{
System.out.println("-------------------------------");
System.out.println("資料庫資料擷取成功!");
}
}
}
執行結果:
後注:
若連接配接MySQL資料庫中出現:Public Key Retrieval is not allowed(不允許解鎖公鑰)
解決方法:
源代碼:
String url = "jdbc:mysql://localhost:3306/test?&useSSL=false&serverTimezone=UTC";
改為:
String url = "jdbc:mysql://localhost:3306/test&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
也就是在其後添加:
allowPublicKeyRetrieval=true