JDBC(Java Data Base Connectivity)是一種用於執行SQL語句的Java API可以為多種關聯式資料庫提供統一訪問它由一組用Java語言編寫的類和介面組成。
-
載入JDBC驅動程式
在串連資料庫之前首先要載入想要串連的資料庫的驅動到JVMJava虛擬機器這通過java.lang.Class類的靜態方法forName(String className)實現。
例如
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(ClassNotFoundException e){
System.out.println("找不到驅動程式類載入驅動失敗");
e.printStackTrace();
}
成功載入後會將Driver類的執行個體註冊到DriverManger類中。
-
提供JDBC串連的URL
串連URL定義了串連資料庫時的協議子協議資料來源標識。
書寫形式協議:子協議:資料來源標識
協議在JDBC中總是以jdbc開始
子協議是橋串連的驅動程式或是資料庫管理系統名稱
資料來源標識標記找到資料庫來源的地址與串連連接埠。
例如Mysql的串連URL
jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=gdk;
其中useUnicode=true: 表示使用Unicode字元集。如果characterEncoding設定為gb2312或GBK本參數必須設定為true。characterEncoding=gbk: 字元編碼方式。
-
建立資料庫連接
要串連資料庫想要向java.sql.DriverManager請求並獲得Connection對象該對象就代表一個資料庫的串連。
使用DriverManager的getConnection(String url, String username, String password)方法傳入指定的欲串連的資料庫的路徑資料庫的使用者名稱和密碼來獲得。
例如
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "root";
try{
Connection con = DriverManager.getConnection(url, username, password);
}catch(SQLException e){
System.out.println("資料庫連接失敗");
e.printStackTrace();
}
-
建立一個Statement
要執行SQL語句必須獲得java.sql.Statement執行個體Statement執行個體分為以下3種類型
1.執行靜態SQL語句。通常通過Statement執行個體實現。
2.執行動態SQL語句。通常通過PreparedStatement執行個體實現。
3.執行資料庫預存程序。通常通過CallableStatement執行個體實現。
具體實現方式
Statement stmt = con.createStatement();
preparedStatement pstmt = con.prepareStatement(sql);
CallableStatement cstmt=con.prepareCall("{CALL demoSp(?,?)}";
-
執行SQL語句
Statement介面提供了三種執行SQL語句的方法executeQuery, executeUpdate和execute
1. ResultSet executeQuery(String sqlString): 執行查詢資料庫的SQL語句返回一個結果集ResutltSet對象。
2. int executeUpdate(String sqlString): 用於執行INSERT, UPDATE或DELETE語句以及SQL DDL語句如CREATE TABLE和DROP TABLE等。
3. execute(sqlString):用於執行返回多個結果集多個更新計數或二者組合的語句。
具體實現的代碼
ResultSet rs = stmt.executeQuery("SELECT * FROM ...");
int rows = stmt.executeUpdate("INSERT INTO ...");
boolean flag = stmt.execute(String sql);
-
處理結果
兩種情況
1. 執行更新返回的是本次操作影響到的記錄數。
2. 執行查詢返回的結果是一個ResultSet對象。
ResultSet包含符合SQL語句中條件的所有行並且它通過一套get方法提供了對這些行中資料的訪問。
使用結果集ResultSet對象的存取方法擷取資料
while(rs.next()){
String name=rs.getString("name");
String pass=rs.getString("1");
} //列是從左至右編號的並且從列1開始
-
關閉JDBC對象
操作完成以後要把所有使用的JDBC對象全都關閉以釋放JDBC資源關閉順序和聲明順序相反
1. 關閉記錄集
2. 關閉聲明
3. 關閉連線物件
if(rs!=null){ //關閉記錄集
try{
Step1. 建立一個Maven項目。
650) this.width=650;" src="http://s3.51cto.com/wyfs02/M00/6F/04/wKioL1WPwt-QDzr7AAI7EjhHTs0341.jpg" title="開啟eclipse" alt="wKioL1WPwt-QDzr7AAI7EjhHTs0341.jpg" />
650) this.width=650;" src="http://s3.51cto.com/wyfs02/M00/6F/07/wKiom1WPwiGgfKn3AANceK5ceBg699.jpg" title="2.png" alt="wKiom1WPwiGgfKn3AANceK5ceBg699.jpg" />