詳解Java的JDBC中Statement與PreparedStatement對象
一旦獲得一個連接,我們可以與數據庫進行交互。在JDBC Statement, CallableStatement 和 PreparedStatement 接口定義的方法和屬性,使可以發(fā)送SQL或PL/SQL命令和從數據庫接收數據。
它們還定義方法,幫助Java和數據庫使用SQL數據類型之間轉換數據的差異。
下表提供了每個接口的用途概要,了解決定使用哪個接口
Statement 對象:
創(chuàng)建Statement對象
在可以使用Statement對象執(zhí)行SQL語句,需要使用Connection對象的createStatement( )方法創(chuàng)建一個,如下面的示例所示:
Statement stmt = null; try { stmt = conn.createStatement( ); . . . } catch (SQLException e) { . . . } finally { . . . }
一旦創(chuàng)建了一個Statement對象,然后可以用它來與它的三個執(zhí)行方法之一執(zhí)行SQL語句。
boolean execute(String SQL) : 如果ResultSet對象可以被檢索返回布爾值true,否則返回false。使用這個方法來執(zhí)行SQL DDL語句,或當需要使用真正的動態(tài)SQL。
int executeUpdate(String SQL) : 返回受影響的SQL語句執(zhí)行的行的數目。使用此方法來執(zhí)行,而希望得到一些受影響的行的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 提供動態(tài)參數的靈活性。
創(chuàng)建PreparedStatement 對象:
PreparedStatement pstmt = null; try { String SQL = "Update Employees SET age = ? WHERE id = ?"; pstmt = conn.prepareStatement(SQL); . . . } catch (SQLException e) { . . . } finally { . . . }
在JDBC中所有的參數都被代表?符號,這是已知的參數標記。在執(zhí)行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 packages import 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 : 1 ID: 100, Age: 18, First: Zara, Last: Ali ID: 101, Age: 25, First: Mahnaz, Last: Fatma ID: 102, Age: 35, First: Zaid, Last: Khan ID: 103, Age: 30, First: Sumit, Last: Mittal Goodbye!
相關文章
[Spring MVC]-詳解SpringMVC的各種參數綁定方式
本篇文章主要介紹了SpringMVC的各種參數綁定方式 ,具有一定的參考價值,有需要的可以了解一下。2016-12-12SpringBoot詳細講解如何創(chuàng)建及刷新Spring容器bean
前面看spring源碼時可以發(fā)現refresh()方法十分重要。在這個方法中會加載beanDefinition,同時創(chuàng)建bean對象。那么在springboot中有沒有使用這個refresh()方法呢2022-06-06SpringBoot優(yōu)雅地實現全局異常處理的方法詳解
這篇文章主要為大家詳細介紹了SpringBoot如何優(yōu)雅地實現全局異常處理,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2022-08-08