JDBC常用類和介面及基本操作示例
JDBC常用類和介面
java.sql.Driver介面
JDBC是一套協議,是Sun定義的一組介面。這個介面規範了你作為Java開發人員該怎麼去訪問下面的資料庫。但這只是一個介面,一種規範。具體介面的實現,是資料庫廠商以驅動的形式實現的。因此,首先要載入驅動,也就是生成一個相應Driver介面的例項。方法如下:
Class.forName("JDBCDriverClass");
注意,對於下載的驅動類,首先需將下載的.jar包連同其路徑一同加入環境變數CLASSPATH中。如果用eclipse或者intelliJ等整合開發環境,可以將驅動匯入指定專案中。匯入方法點這裡jdbc-mysql驅動包
java.sql.DriverManager類
驅動程式管理器類,負責管理各種不同的驅動程式。驅動程式載入後,可通過該類的靜態方法getConnection(URL)
連線到一個數據庫,並返回一個Connection物件。URL是資料庫在Internet上的唯一識別符號。以下列出常見資料庫URL格式:
Access jdbc:odbc:dataSource
MySQL jdbc:mysql://hostname/dbname
Oracle jdbc:oracle:thin:@hostname:port#:oracleDBSID
建立連線方式如下:
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/Student", "easy", "123456");
該語句為本地MySQL資料庫Student建立一個連線,使用者名稱為easy,使用者口令為123456。
java.sql.Connection介面
該介面的物件,表示與指定資料庫的連線。只有連線成功後,才能執行後續有關資料庫的所有操作。
java.sql.Statement介面
Connection物件好比連線本地程式和資料庫之間的纜繩,代表著程式與資料庫之間的連線。Statement物件就好比纜車,它將SQL語句傳送給資料庫並返回結果。簡單地說,使用Connection連線到資料庫,由Statement建立和執行SQL語句。
Statement statement = connection.createStatement();
Statement物件的executeQuery()方法,執行SELECT查詢語句。
Statement物件的executeUpdate()方法,執行INSERT、UPDATE、DELETE等語句。
Statement物件的execute()方法,執行CREATE、DROP等語句。
java.sql.ResultSet介面
針對有返回結果的SQL語句,ResultSet介面用來處理結果。其中存有一個表,該表的當前行(初始位置為null)可以被訪問。呼叫其next()方法可以將當前行下移,呼叫其get()方法可以從當前行獲取值。
JDBC基本操作示例
在MySQL建立使用者賬戶
在DOS命令列下依次執行以下語句:(注意忽略雙斜槓後面的內容)
mysql -uroot -p //以root使用者身份登入到MySQL,-p後為root使用者密碼
use mysql //進入(切換)到mysql資料庫
create user 'easy'@localhost identified by '123456'; //建立名為easy使用者密碼為123456的使用者
grant select,insert,update,delete,create,drop,execute,
references on *.* to 'easy'@'localhost'; //給新建的使用者賬戶授權
exit
注:Windows系統下,每次計算機啟動時會啟動MySQL資料庫伺服器,該伺服器預設包含一個名為mysql的資料庫,其中存放包含伺服器資訊及使用者資訊的表格。該資料庫為管理員的使用而設計,我們就是在這個資料庫中建立使用者賬戶的。
建立名為Student的資料庫
在DOS下依次輸入以下命令:(注意忽略雙斜槓後面的內容)
mysql -ueasy -p123456 //以easy使用者身份登入到MySQL
create database Student; //建立名為Student的資料庫
建立StudentInfo資料表
將以下語句寫到一個指令碼檔案中:
create table StudentInfo (
id varchar(10) primary key,
name varchar(50),
age integer(3));
insert into StudentInfo values('U08001', 'Jim', 18);
insert into StudentInfo values('U08002', 'Tom', 20);
insert into StudentInfo values('U08003', 'Lily', 20);
不妨將指令碼檔案命名為script.sql。
接下來繼續執行以下命令:
use Student //進入(切換)到Student資料庫
source script.sql; //執行該SQL指令碼檔案
注意,在執行source script.sql
之前,要確保當前路徑下包含script.sql檔案。如果提示找不到檔案,先退出mysql進入到script.sql目錄下重新登入mysql執行。
至此,我們建立了Student資料庫,並在該資料庫中建立了StudentInfo表,其中插入了三條資料(見指令碼檔案中三條insert
)。
列印StudentInfo表中內容
新建工程後新增以下程式碼:
import java.sql.*;
public class SQLtest {
public static void main(String args[]) {
Connection connection = null;
try{
//load driver
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded!");
//Establish a connection
connection = DriverManager.getConnection
("jdbc:mysql://localhost/Student", "easy", "123456");
System.out.println("Database connected!");
//create a statement
Statement statement = connection.createStatement();
//execute a statement
ResultSet rs = statement.executeQuery("select * from StudentInfo");
while(rs.next()) {
System.out.print("學號" + rs.getString(1));
System.out.print("\t姓名" + rs.getString(2));
System.out.print("\t年齡" + rs.getString(3));
System.out.println();
}
}catch (ClassNotFoundException ce) {
ce.printStackTrace();
}catch (SQLException sqle) {
sqle.printStackTrace();
}finally {
try {
connection.close();
}catch (SQLException sqle) {
sqle.printStackTrace();
}
}
}
輸出如下:
Driver loaded!
Database connected!
學號U08001 姓名Jim 年齡18
學號U08002 姓名Tom 年齡20
學號U08003 姓名Lily 年齡20
11行 載入mysql驅動
15行 以’easy’使用者建立到“localhost”本地伺服器中Student資料庫的連線。
20行 建立Statemen物件
23行 執行SQL語句”select * from StudentInfo”,實現對StudentInfo表的查詢,並將結果返回ResultSet物件。
25行 遍歷打印表中資料
資料庫伺服器建立和維護一個連線的開銷較大,作為一種良好程式設計習慣,當不再使用ResultSet,Statement及Connection物件時,應手動關閉。實際上,在呼叫Statement物件的close()方法時,其上如果有開啟的ResultSet結果集,會自動關閉。同樣地,呼叫Connection物件的close()方法時,基於該連線的所有Statement物件都將被關閉。如果我們使用的連線是短時性的,可以在finally語句塊中只顯式關閉Connection物件。
修改StudentInfo表內容並列印
23行 在StudentInfo表中插入'U08004', 'LiLei', '19'
26行 將所有學生年齡加2
29行 刪除學號為U08002
的學生
import java.sql.*;
public class SQLtest {
public static void main(String args[]) {
Connection connection = null;
try{
//load driver
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded!");
//Establish a connection
connection = DriverManager.getConnection
("jdbc:mysql://localhost/Student", "easy", "123456");
System.out.println("Database connected!");
//create a statement
Statement statement = connection.createStatement();
//插入新資料
statement.executeUpdate("insert into StudentInfo values('U08004', 'LiLei', '19')");
//將所有學生年齡加2
statement.executeUpdate("update StudentInfo set age=age+2");
//刪除學號為U08002的資料項
statement.executeUpdate("delete from StudentInfo where id='U08002'");
//execute a statement
ResultSet rs = statement.executeQuery("select * from StudentInfo");
while(rs.next()) {
System.out.print("學號" + rs.getString(1));
System.out.print("\t姓名" + rs.getString(2));
System.out.print("\t年齡" + rs.getString(3));
System.out.println();
}
}catch (ClassNotFoundException ce) {
ce.printStackTrace();
}catch (SQLException sqle) {
sqle.printStackTrace();
}finally {
try {
connection.close();
}catch (SQLException sqle) {
sqle.printStackTrace();
}
}
}
列印結果如下:
Driver loaded!
Database connected!
學號U08001 姓名Jim 年齡20
學號U08003 姓名Lily 年齡22
學號U08004 姓名LiLei 年齡21