詳解Java的JDBC中Statement與PreparedStatement對象_java

來源:互聯網
上載者:User

一旦獲得一個串連,我們可以與資料庫進行互動。在JDBC Statement, CallableStatement 和 PreparedStatement 介面定義的方法和屬性,使可以發送SQL或PL/SQL命令和從資料庫接收資料。

它們還定義方法,協助Java和資料庫使用SQL資料類型之間轉換資料的差異。

下表提供了每個介面的用途概要,瞭解決定使用哪個介面

Statement 對象:

建立Statement對象
在可以使用Statement對象執行SQL語句,需要使用Connection對象的createStatement( )方法建立一個,如下面的樣本所示:

Statement stmt = null;try {  stmt = conn.createStatement( );  . . .}catch (SQLException e) {  . . .}finally {  . . .}

一旦建立了一個Statement對象,然後可以用它來與它的三個執行方法之一執行SQL語句。

boolean execute(String SQL) : 如果ResultSet對象可以被檢索返回布爾值true,否則返回false。使用這個方法來執行SQL DDL語句,或當需要使用真正的動態SQL。

int executeUpdate(String SQL) : 返回受影響的SQL語句執行的行的數目。使用此方法來執行,而希望得到一些受影響的行的SQL語句 - 例如,INSERT,UPDATE或DELETE語句。

ResultSet executeQuery(String SQL) : 返回ResultSet對象。當希望得到一個結果集使用此方法,就像使用一個SELECT語句。

關閉 Statement 對象:
正如關閉一個Connection對象來儲存資料庫資源,出於同樣的原因,也應該關閉Statement對象。

close()方法簡單的調用將完成這項工作。如果關閉了Connection對象首先它會關閉Statement對象也是如此。然而,應該始終明確關閉Statement對象,以確保正確的清除。

Statement stmt = null;try {  stmt = conn.createStatement( );  . . .}catch (SQLException e) {  . . .}finally {  stmt.close();}


PreparedStatement 對象
PreparedStatement介面擴充了Statement介面,讓過一個通用的Statement對象增加幾個進階功能。

statement 提供動態參數的靈活性。

建立PreparedStatement 對象:

PreparedStatement pstmt = null;try {  String SQL = "Update Employees SET age = ? WHERE id = ?";  pstmt = conn.prepareStatement(SQL);  . . .}catch (SQLException e) {  . . .}finally {  . . .}

在JDBC中所有的參數都被代表?符號,這是已知的參數標記。在執行SQL語句之前,必須提供值的每一個參數。

setXXX()方法將值綁定到參數,其中XXX表示希望綁定到輸入參數值的Java資料類型。如果忘了提供值,將收到一個SQLException。

每個參數標記是由它的序號位置引用。第一標記表示位置1,下一個位置為2 等等。這種方法不同於Java數組索引,以0開始。

所有的Statement對象的方法來與資料庫互動(a) execute(), (b) executeQuery(), 及(c) executeUpdate() 也與PreparedStatement對象的工作。然而,該方法被修改為使用SQL語句,可以利用輸入的參數。

關閉PreparedStatement對象:
正如關閉Statement對象,出於同樣的原因,也應該關閉的PreparedStatement對象。

close()方法簡單的調用將完成這項工作。如果關閉了Connection對象首先它會關閉PreparedStatement對象。然而,應該始終明確關閉PreparedStatement對象,以確保正確的清除。

PreparedStatement pstmt = null;try {  String SQL = "Update Employees SET age = ? WHERE id = ?";  pstmt = conn.prepareStatement(SQL);  . . .}catch (SQLException e) {  . . .}finally {  pstmt.close();}

PreparedStatement執行個體
以下是這使得使用PreparedStatement以及開啟和關閉statments的例子:
複製下面的例子中JDBCExample.java,編譯並運行,如下所示:

//STEP 1. Import required packagesimport java.sql.*;public class JDBCExample {  // 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;  PreparedStatement 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...");   String sql = "UPDATE Employees set age=? WHERE id=?";   stmt = conn.prepareStatement(sql);      //Bind values into the parameters.   stmt.setInt(1, 35); // This would set age   stmt.setInt(2, 102); // This would set ID      // Let us update age of the record with ID = 102;   int rows = stmt.executeUpdate();   System.out.println("Rows impacted : " + rows );   // Let us select all the records and display them.   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 JDBCExample

現在來編譯上面的例子如下:

C:>javac JDBCExample.java

當運行JDBCExample,它會產生以下結果:

C:>java JDBCExample
Connecting to database...Creating statement...Rows impacted : 1ID: 100, Age: 18, First: Zara, Last: AliID: 101, Age: 25, First: Mahnaz, Last: FatmaID: 102, Age: 35, First: Zaid, Last: KhanID: 103, Age: 30, First: Sumit, Last: MittalGoodbye!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.