一旦獲得一個連接,我們可以與數(shù)據(jù)庫進(jìn)行交互。在JDBC Statement, CallableStatement 和 PreparedStatement 接口定義的方法和屬性,使可以發(fā)送SQL或PL/SQL命令和從數(shù)據(jù)庫接收數(shù)據(jù)。
它們還定義方法,幫助Java和數(shù)據(jù)庫使用SQL數(shù)據(jù)類型之間轉(zhuǎn)換數(shù)據(jù)的差異。
下表提供了每個接口的用途概要,了解決定使用哪個接口
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語句,或當(dāng)需要使用真正的動態(tài)SQL。
int executeUpdate(String SQL) : 返回受影響的SQL語句執(zhí)行的行的數(shù)目。使用此方法來執(zhí)行,而希望得到一些受影響的行的SQL語句 - 例如,INSERT,UPDATE或DELETE語句。
ResultSet executeQuery(String SQL) : 返回ResultSet對象。當(dāng)希望得到一個結(jié)果集使用此方法,就像使用一個SELECT語句。
關(guān)閉 Statement 對象:
正如關(guān)閉一個Connection對象來保存數(shù)據(jù)庫資源,出于同樣的原因,也應(yīng)該關(guān)閉Statement對象。
close()方法簡單的調(diào)用將完成這項(xiàng)工作。如果關(guān)閉了Connection對象首先它會關(guān)閉Statement對象也是如此。然而,應(yīng)該始終明確關(guān)閉Statement對象,以確保正確的清除。
Statement stmt = null;try { stmt = conn.createStatement( ); . . .}catch (SQLException e) { . . .}finally { stmt.close();}
PreparedStatement 對象
PreparedStatement接口擴(kuò)展了Statement接口,讓過一個通用的Statement對象增加幾個高級功能。
statement 提供動態(tài)參數(shù)的靈活性。
創(chuàng)建PreparedStatement 對象:
PreparedStatement pstmt = null;try { String SQL = "Update Employees SET age = ? WHERE id = ?"; pstmt = conn.prepareStatement(SQL); . . .}catch (SQLException e) { . . .}finally { . . .}
在JDBC中所有的參數(shù)都被代表?符號,這是已知的參數(shù)標(biāo)記。在執(zhí)行SQL語句之前,必須提供值的每一個參數(shù)。
setXXX()方法將值綁定到參數(shù),其中XXX表示希望綁定到輸入?yún)?shù)值的Java數(shù)據(jù)類型。如果忘了提供值,將收到一個SQLException。
每個參數(shù)標(biāo)記是由它的序號位置引用。第一標(biāo)記表示位置1,下一個位置為2 等等。這種方法不同于Java數(shù)組索引,以0開始。
所有的Statement對象的方法來與數(shù)據(jù)庫交互(a) execute(), (b) executeQuery(), 及(c) executeUpdate() 也與PreparedStatement對象的工作。然而,該方法被修改為使用SQL語句,可以利用輸入的參數(shù)。
關(guān)閉PreparedStatement對象:
正如關(guān)閉Statement對象,出于同樣的原因,也應(yīng)該關(guān)閉的PreparedStatement對象。
close()方法簡單的調(diào)用將完成這項(xiàng)工作。如果關(guān)閉了Connection對象首先它會關(guān)閉PreparedStatement對象。然而,應(yīng)該始終明確關(guān)閉PreparedStatement對象,以確保正確的清除。
PreparedStatement pstmt = null;try { String SQL = "Update Employees SET age = ? WHERE id = ?"; pstmt = conn.prepareStatement(SQL); . . .}catch (SQLException e) { . . .}finally { pstmt.close();}
PreparedStatement實(shí)例
以下是這使得使用PreparedStatement以及打開和關(guān)閉statments的例子:
復(fù)制下面的例子中JDBCExample.java,編譯并運(yùn)行,如下所示:
//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
現(xiàn)在來編譯上面的例子如下:
C:>javac JDBCExample.java
當(dāng)運(yùn)行JDBCExample,它會產(chǎn)生以下結(jié)果:
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!
新聞熱點(diǎn)
疑難解答
圖片精選