JDBC API訪問數據庫的基本步驟。


JDBC本質:官方定義了一套操作所有關系型數據庫的規則(接口),各個數據庫廠商實現這個接口,提供數據庫驅動jar包。

  我們可以使用這套接口(JDBC)編程,真正執行的代碼是驅動jar包中的實現類。

任何一個Java應用程序使用JDBC API訪問數據庫,其基本工作可以分為5個步驟:

(1)加載JDBC驅動程序;

(2)建立數據庫連接;

(3)創建操作數據庫SQL的Statement、PreparedStatement或CallableStatement對象;

(4)執行語句並分析執行結果;

(5)關閉連接。

 

 

1、加載JDBC驅動程序

    利用Class類的方法forName(String driverName)加載JDBC驅動,不同的數據庫的JDBC驅動名稱不同,MySql的驅動類名為com.mysql.jdbc.Driver。

Class forName("com.mysql.jdbc.Driver");

    //注意:
      //在Java Web應用開發中,如果要訪問數據庫,首先應將加載數據庫的JDBC驅動程序(jar包)復制到Web應用程序的WEB-INF\lib 目錄下,這樣Web應用程序才能正常地通過JDBC接口訪問數據庫。

2、建立數據庫的連接

    利用DriverManager類的方法getConnection()獲得與特定數據庫的連接實例(Connection實例)。例如創建一個連接的本地MySQL數據庫userdb Connection對象,假設該數據庫的用戶名為root、密碼為passwd,代碼如下:

    //第一種方式:
      String url = "jdbc:mysql://localhost:3306/userdb?user = root & password = passwd";       Connection con = DriverManager.getConnection(url);     //第二種方式:
      private static final String url = "jdbc:mysql://localhost:3306/userdb";       private static final String user = "root";       private static final String password = "111111";       protected static Connection con = null;       con = DriverManager.getConnection(url , user , password);

 

3、進行數據庫操作

    對數據庫的操作依賴於SQL語句,JDBC依據SQL語句的類型不同提供了三種執行SQL的對象,即Statement,PreparedStatement和CallableStatement。

    1)Statement對象執行靜態SQL語句

    Statement對象用於執行不含參數的靜態SQL語句,JDBC利用Connection實例的createStatement()方法創建一個Statement實例,通過Statement實例的execute()方法(不常用)、executeQuerry()方法(select)或者executeUpdate()方法(insert、update或 delete)等執行SQL語句。例如查詢數據   表tb_users中的所有記錄:

  //創建Statement對象,其中con為Connection對象
    Statement statement = con.createStatement();   
  //使用executeQuery()方法執行SELECT語句,該方法的返回值為ResultSet類型  
   ResultSet rs = statement.executeQuerry(select*fron tb_users);

    再如,刪除數據表tb_users中的fd_username 為Allen的記錄:

  //創建Statement對象,其中con為Connection對象
    Statement statement = con.createStatement();
  
//使用executeUpdate()方法執行INSERT、UPDATE、DELETE等SQL語句,返回 int 類型
   int result = 0;      result = statement.executeUpdate("delete from tb_users where fd_username = 'Allen' ");

    2)PreparedStatement 執行動態SQL語句

    PreparedStatement用於執行含有動態的SQL語句,動態SQL語句是指在程序運行時能動態地為SQL語句的參數賦值,增加了程序的靈活性。PreparedStatement 對象由Connection 實例的 preparedStatement(String sql)方法構建。

      PreparedStatement 接口也有executeQuery()和executeUpdate()方法,但這兩個方法都不帶參數。該接口提供了setXxx(int paramIndex , xxx  var)方法為動態的SQL語句中的參數賦值。這里仍以上面的SQL操作為例說明PreparedStatement 對象     的創建和相關方法的使用。

  // 聲明動態SQL ,參數使用?占位符表示
    String sqlSelect = "select * from tb_users where fd_username = ?";
  
//創建PreparedStatement 對象psQuery,其中con為Connection對象     PreparedStatement PSQuery = con. preparedStatement(sqlSelect);
  
/*為動態SQL語句中的參數賦值,由於fd_username為Sting類型,故使用setString()方法為參數賦值,1代表動態SQL語句中的第一個問題(第一個問號處值)*/     psQuery.setString(1,"Allen");
    String sqlDelete = "delete from tb_users where fd_username = ?";
//創建PreparedStatement 對象 psUpdate ,其中con為Connection對象    PreparedStatement psUpdate = con.preparedStatement(sqlDelete);
  
//使用executeUpdate()方法執行INSERT、UPDATE、DELETE等SQL語句,這里列舉的是 刪除
  ResultSet result = psUpdate.executeUpdate();
 
        

4、對執行結果進行分析處理

    1)分析查詢結果集 ResultSet

    在執行SELECT語句后必然產生一個ResultSet結果集實例,對結果集進行分析與處理是應用程序的最終目標,可以使用循環遍歷結果集中的每一行記錄,使用getXxx()方法獲取遍歷記錄行指定列的數據。

  //查詢tb_users表中記錄的用戶名和性別
    ResultSet rs = statement.executeQuerry("select fd_username , fd_gender from tb_users");
  //使用next() 方法判斷結果集是否有下一行,從而遍歷結果集中的所有記錄行
    while(rs.next()){
    //獲取遍歷記錄行中列名fd_username的對應值
      String username = rs.getString("fd_username");
    //獲取遍歷記錄行中第二列的對應值
      String gender = rs.getString(2);
      System.out.println("用戶名:"+ username + ",性別:"+ gender);

    2)分析執行結果

    對於INSERT、UPDATE、DELETE甚至是SQL DLL語句,一般由executeUpdate()方法執行且返回值為int 類型,表示受影響的記錄行數,如返回值大於0表示該SQL語句成功執行。

    int result = 0;
    String sql = "delete from tb_users where fd_username = 'Allen' ";
  // execteUpdate()方法執行INSERT、UPDATE、DELETE等SQL語句,返回int類型
    result = statement.executeUpdate(sql);
  //分析執行結果
    if(result > 0){
        System.out.println("刪除成功!");
    else
        System.out.println("刪除失敗!");

5、關閉JDBC相關對象

應用程序在對數據庫操作完成以后,要把使用的所有JDBC對象全部關閉,以釋放JDBC資源,關閉順序和聲明順序正好相反。

(1)關閉結果集ResultSet 對象;

(2)關閉Statement、PreparedStatement對象;

(3)關閉連接對象

//關閉結果集rs
if (rs != null){
  try {
       rs.close();
     } catch (SQLException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     }
}
//關閉Statement對象statement
if (statement!= null) {
    try {
       statement.close();
     } catch (SQLException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     }
 }
//關閉連接對象 con
if (con!= null) {
    try {
       con.close();
     } catch (SQLException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     }
}

 

 

 

 

  Java應用程序用過JDBC操作5個基本步驟。首先加載JDBC驅動,使用DriverManage對象創建Connection實例與制定的數據庫建立連接;

然后使用Connection實例的createStatement()方法創建Statement實例(也可以創建PreparedStatement和CallableStatement對象),

並利用Statement實例的executeQuery()方法執行INSERT、UPDATE、DELETE等語句,並通過分析與處理執行結果實現應用程序的具體功能,

最后務必關閉與數據庫之間的連接。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM