今天看了看jdbc,java.sql包和sqlserver2005的sqljdbc.jar,大體上明白了,jdbc是sun公司發布的一套資料庫實現標準,只提供介面,不具體實現。具體的實現過程由各資料庫開發廠商決定。各資料庫開發廠商需要提供一個用於實現上述介面的.jar包。
這樣做得好處是,如果有一天變更資料庫(如從sqlserver轉換成為oracle資料庫),只需要更改java程式中的資料庫驅動程式,和將sqljdbc.jar更改為oracle提供的.jar包就可以了。當然,如果使用了oracle不識別的函數,再改一下函數就就可以了。不用修正java代碼。因為java代碼中不使用具體的資料庫開發廠商實現的類,而是使用java.sql中定義的介面。真是太方便了。
java.sql包中主要的類和介面包括:
1 Connection介面,定義為:public interface Connection
2 Driver介面,定義為:public interface Driver
3 DriverManager類,定義為:public class DriverManager
4 PreparedStatement介面,定義為:public interface PreparedStatement extends Statement
5 ResultSet介面,定義為:public interface ResultSet
6 SQLException類,定義為:public class SQLException extends java.lang.Exception
7 Statement介面,定義為:public interface Statement
我們一般使用jdbc的模式是:
1 載入資料庫驅動程式
2 串連資料
3 執行SQL語句,並返回執行狀態和查詢結果
4 關閉資料庫連接
轉換為代碼:
- import java.sql.*;
- public class TestDBConnection {
- public static void main(String[] args) {
-
- try {
- //定義一個串連
- Connection con;
-
- //載入各資料庫開發廠商實現的JDBC驅動程式
- //mysql的場合:com.mysql.jdbc.Driver
- Class.forName("com.mysql.jdbc.Driver");
-
- //串連資料庫(各資料庫開發廠商不同)
- //以下兩種寫法都可以(對於mysql來說)
- con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","root","sa");
//con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb?user=root&password=sa");
- //建立Statement對象或者PreparedStatement對象
- //Statement:一般的Statement對象
- //PreparedStatement:用於動態SQL的Statement對象
- Statement st = con.createStatement();
-
- String sql = "select * from table1 order by id";
-
- //定義ResultSet對象
- //執行SQL操作(查詢,更新)
- //executeQuery:查詢
- //executeUpdate:更新
- //execute:一般不使用
- ResultSet rs = st.executeQuery(sql);
-
- while (rs.next()) {
-
- //根據列索引取得資料
- System.out.println(rs.getString(1));
- //根據列名取得資料
- System.out.println(rs.getString("columnName"));
- }
- //關閉資源
- if (rs != null) rs.close();
- if (st != null) st.close();
- if (con != null) con.close();
-
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- }
- }