国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

詳解Java的JDBC中Statement與PreparedStatement對象

2019-11-26 14:43:58
字體:
供稿:網(wǎng)友

一旦獲得一個連接,我們可以與數(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ù)的差異。

下表提供了每個接口的用途概要,了解決定使用哪個接口

2015122585343394.png (571×206)

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!
發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 酒泉市| 水城县| 大宁县| 建阳市| 恩平市| 贵港市| 兴隆县| 出国| 宁城县| 呼玛县| 临沭县| 奉新县| 嫩江县| 萍乡市| 阜宁县| 格尔木市| 桃园市| 揭东县| 宁化县| 涞水县| 商水县| 工布江达县| 垣曲县| 三都| 晋城| 永平县| 灵台县| 连南| 邯郸市| 肃宁县| 华坪县| 邵阳市| 定安县| 长汀县| 长顺县| 五常市| 石狮市| 白城市| 商河县| 汕头市| 四平市|