JDBC是什么?
JDBC,是一種用于Java編程語言和多種數(shù)據(jù)庫連接的標(biāo)準(zhǔn)Java API。
JDBC庫提供的多種API可以完成如下的幾個和數(shù)據(jù)庫相關(guān)的任務(wù):
- 和數(shù)據(jù)庫建立連接。
- 創(chuàng)建 SQL 或 MySQL 聲明。
- 在數(shù)據(jù)庫中執(zhí)行 SQL 或 MySQL 查詢。
- 展示或修改數(shù)據(jù)庫中的記錄。
之所以提供以上功能,是為了實現(xiàn)將Java編程代碼和數(shù)據(jù)庫相分離的目的。這樣可以使得Java編寫的可執(zhí)行程序可以通過同樣的JDBC API連接不同的數(shù)據(jù)庫,而僅僅是改變數(shù)據(jù)庫驅(qū)動,這樣更有利于數(shù)據(jù)庫的選擇。

JDBC的作用
JDBC 組件
JDBC API 提供了一些接口和類以便使用:
- DriverManager:該類被用于管理數(shù)據(jù)庫驅(qū)動。當(dāng)Java應(yīng)用發(fā)送一個數(shù)據(jù)庫連接請求時,會伴隨一個對應(yīng)數(shù)據(jù)庫的驅(qū)動連接子協(xié)議。這個協(xié)議會通過DriverManager發(fā)送到各個Driver,而第一個識別該協(xié)議的Dirver會在對應(yīng)的數(shù)據(jù)庫和JDBC接口間建立連接。
- Driver:驅(qū)動接口負責(zé)處理與數(shù)據(jù)庫服務(wù)器之間的通信。Java編程人員很少會直接使用到這個接口,這是用于DriverManager類在管理著Driver接口。
- Connection:這個接口包含了所有連接數(shù)據(jù)庫相關(guān)的方法。一個connection對象會包含了和數(shù)據(jù)庫通信的上下文等信息。所有與數(shù)據(jù)庫相關(guān)的通信都且僅需要通過connection對象。
- Statement:該接口負責(zé)將Java代碼中嵌入的SQL語句提交到數(shù)據(jù)庫,另外還有一些派生出的接口可以完成參數(shù)的傳遞和存儲過程的執(zhí)行。
- ResultSet:通過Statement對象執(zhí)行的查詢語句的查詢結(jié)果將被通過ResultSet對象從數(shù)據(jù)庫取回。ResultSet對象可以像迭代器一樣去操作數(shù)據(jù)。
- SQLException:這個類用來處理數(shù)據(jù)庫應(yīng)用中出現(xiàn)的各種錯誤。
JDBC Template
下面給出一個JDBC連接數(shù)據(jù)庫的模板,雖然已經(jīng)很少使用了,但是會幫助理解連接流程。
//STEP 1.
Import required packagesimport java.sql.*;
public class FirstExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
// Database credentials
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id"); int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){ //Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){ //Handle errors for Class.forName
e.printStackTrace();
}finally{ //finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){ }// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end FirstExample