1.首先下載合適的驅(qū)動包,8版本所用驅(qū)動jar包和5版本有出入,下載8版本地址如下:
鏈接:https://pan.baidu.com/s/1YJudxw01tG9PGBVxMZntkg
提取碼:jbml
2.在eclipse 新建(java工程)java project,并導入第一步下載的jar包,新建一個類如JdbcDemo如圖:
image.png

image.png
3.編寫JdbcDemo 程序
具體實現(xiàn)步驟如下:
- 注冊驅(qū)動
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
2.創(chuàng)建和數(shù)據(jù)庫的連接對象:是Connection接口的實現(xiàn)類對象
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/testJdbc?" + "user=root&password=123456&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false");
3.獲取Sql語句的執(zhí)行者對象,是Statement接口的實現(xiàn)類對象
Statement stmt = conn.createStatement();
4.獲取結(jié)果集對象,是ResultSet接口的實現(xiàn)類對象
ResultSet rs = stmt.executeQuery("select* from user");
5.處理結(jié)果集
while (rs.next()) {
Object id = rs.getObject("id");
Object username = rs.getObject("username");
System.out.println(id+"==="+username);
}
6.釋放資源
rs.close();
stmt.close();
conn.close();
整個示例代碼如下:
package com.liquan;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcDemo {
public static void main(String[] args){
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
conn =
DriverManager.getConnection("jdbc:mysql://localhost/testJdbc?" +
"user=root&password=123456&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false");
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM user");
while(rs.next()){
Object id = rs.getObject("id");
Object username = rs.getObject("username");
System.out.println(id+"==="+username);
}
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
// it is a good idea to release
// resources in a finally{} block
// in reverse-order of their creation
// if they are no-longer needed
if (rs != null) {
try {
rs.close();
} catch (SQLException sqlEx) { } // ignore
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { } // ignore
stmt = null;
}
}
}
}
ps: 使用的過程中可能會出現(xiàn)連接錯誤等,有可能的原因是mysql8默認開啟了安全認證,或者是因為時區(qū)的原因造成的,因此創(chuàng)建連接的時候可以制定一些連接參數(shù)如:
useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false