本章節我們為大家介紹 Java 如何使用 使用 JDBC 連接 MySQL 數據庫。
Java 連接 MySQL 需要驅動包,最新版下載地址為:http://dev.mysql.com/downloads/connector/j/,解壓后得到 jar 庫文件,然后在對應的項目中導入該庫文件。
你可以下載我提供的 jar 包:mysql-connector-java-5.1.39-bin.jar
本實例使用的是 Eclipse,導入 jar 包:
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");
這是解壓后的文件:
1、新建java項目 然后新建一個文件夾——libs(用來放各種外部包)
右鍵工程名(我的是Mysql)—新建New—文件夾Folder—Folder name為libs—Finish。
2、在包里面加入連接mysql數據庫的包
即剛才解壓后得到的 mysql-connector-java-5.1.45-bin.jar
然后復制粘貼到我們java項目的libs文件夾下面(注意是物理地址里);
此時,在eclipse中—右擊libs文件夾—刷新Refresh,就將下載好的JDBC放到該文件夾下,如下圖所示:
3、構建路徑上的jar包
在eclipse中
a:點擊項目Project——選擇屬性Propeties
b:進行添加
打開屬性Propeties后,點擊java構建路徑(Java Build Path)
點擊添加jar(Add JARs...),選擇你的項目下的jar包,然后確定,最后添加完成
4.查詢代碼
package Operation;
import java.sql.*;
public class Select {
// MySQL 8.0 以下版本 - JDBC 驅動名及數據庫 URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/xyp";
// 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 Sname, Sno FROM student";
ResultSet rs = stmt.executeQuery(sql);
// 展開結果集數據庫
System.out.println("--------------------------------");
System.out.println("學號"+"\t\t"+"姓名"+"\t");
System.out.println("--------------------------------");
while(rs.next()){
// 通過字段檢索
String name = rs.getString("Sname");
String sno = rs.getString("Sno");
// 輸出數據
System.out.println(sno+"\t"+name+"\t");
/*
* System.out.print(" 姓名: " + name+""); System.out.print("學號: " + sno);
*/
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!");
}
}
結果如下:
5.插入代碼
package Operation;
import java.sql.*;
public class Insert {//插入操作
public static void main(String args[])
{
try
{
Class.forName("com.mysql.jdbc.Driver"); //啟動驅動
System.out.println("數據庫啟動成功");
}
catch (ClassNotFoundException ce)
{
System.out.println("SQLException:"+ce.getMessage());
}
try {
java.sql.Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/xyp","root","123456");//連接數據庫 數據庫名 密碼 用戶名
Statement stmt = con.createStatement();
String sqlstr = "insert into Student values('2001131', '謝應鵬',' 男',21,'CS','2021-6-24')";
stmt.executeUpdate(sqlstr);
System.out.println("插入成功");
//stmt.executeUpdate("insert into employee values('2020','翟建設','男',746)");
stmt.close();
con.close(); //關閉連接
}
catch (SQLException e)
{ System.out.println("SQLException:"+e.getMessage()); }
}
}
結果如下:
6.刪除代碼
package Operation;
import java.sql.*;
class Delete{//刪除操作
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("數據庫啟動成功");
}
catch (ClassNotFoundException ce){
System.out.println("SQLException:"+ce.getMessage());
}
try {
java.sql.Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/xyp","root","123456");
Statement stmt = con.createStatement();
String sql = "delete from p where Pno='p1'";
String sql1 = "SET FOREIGN_KEY_CHECKS = 1";
stmt.executeUpdate(sql1);//解決辦法二:不檢查外鏈,設置FOREIGN_KEY_CHECKS變量:
/*
* SET FOREIGN_KEY_CHECKS = 0; DELETE FROM `goods` WHERE `goods_id` = '11'
* 刪除完成后設置 SET FOREIGN_KEY_CHECKS = 1;
*/
stmt.executeUpdate(sql);
System.out.println("刪除成功");
stmt.close();
con.close();
}
catch (SQLException e){
System.out.println("SQLException:"+e.getMessage());
}
}
}
結果如下:
7.更新代碼
package Operation;
import java.sql.*;
class Update{//更新操作
public static void main(String args[]) {
try
{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("數據庫啟動成功");
}
catch (ClassNotFoundException ce){
System.out.println("SQLException:"+ce.getMessage());
}
try{
java.sql.Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/xyp","root","xyp166166");
Statement stmt = con.createStatement();
String sql = "update student set Sage= '31'" + "where Sname= '王敏'";
stmt.executeUpdate(sql);
System.out.println("插入成功");
stmt.close();
con.close();
}
catch (SQLException e){
System.out.println("SQLException:"+e.getMessage());
}
}
}
結果如下:
8、連接mysql數據庫失敗原因分析:
1、數據庫的服務是否打開
2、是否在新建了對應的數據庫
3、是否添加了jar包
4、是否加載了驅動
5、連接字符串、登錄名以及密碼是否有誤
9.聯系方式
qq:2061302791
微信:xie2061302791
電話:15284524485
個人網站:https://xieyingpeng.github.io/
Github:https://github.com/xieyingpeng/
博客園:https://www.cnblogs.com/Xieyingpengz
知乎:https://www.zhihu.com/people/nan-qiao-12-73