編寫一個JDBC程式示例,演示使用PreparedStatement物件進行批次處理?
將相關的SQL語句分組到一個批處理中,然後一次性執行/提交,這被稱為批次處理。Statement介面提供了執行批次處理的方法,例如addBatch()、executeBatch()、clearBatch()。
按照以下步驟使用PreparedStatement物件執行批次更新
使用DriverManager類的**registerDriver()**方法註冊驅動程式類。將驅動程式類名作為引數傳遞給它。
使用DriverManager類的**getConnection()**方法連線到資料庫。將URL(字串)、使用者名稱(字串)、密碼(字串)作為引數傳遞給它。
使用Connection介面的**setAutoCommit()**方法將自動提交設定為false。
使用Connection介面的**prepareStatement()**方法建立一個PreparedStatement物件。將帶有佔位符(?)的查詢(插入)傳遞給它。
使用PreparedStatement介面的setter方法為上述建立的語句中的佔位符設定值。
使用Statement介面的**addBatch()**方法將所需語句新增到批處理中。
使用Statement介面的**executeBatch()**方法執行批處理。
使用Statement介面的**commit()**方法提交所做的更改。
示例
假設我們建立了一個名為**Dispatches**的表,其描述如下
+-------------------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------------------+--------------+------+-----+---------+-------+ | Product_Name | varchar(255) | YES | | NULL | | | Name_Of_Customer | varchar(255) | YES | | NULL | | | Month_Of_Dispatch | varchar(255) | YES | | NULL | | | Price | int(11) | YES | | NULL | | | Location | varchar(255) | YES | | NULL | | +-------------------+--------------+------+-----+---------+-------+
下面的程式使用批次處理(使用prepared statement物件)將資料插入到此表中。
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; public class BatchProcessing_PreparedStatement { public static void main(String args[])throws Exception { //Getting the connection String mysqlUrl = "jdbc:mysql:///sampleDB"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Setting auto-commit false con.setAutoCommit(false); //Creating a PreparedStatement object PreparedStatement pstmt = con.prepareStatement("INSERT INTO Dispatches VALUES (?, ?, ?, ?, ?)"); pstmt.setString(1, "Keyboard"); pstmt.setString(2, "Amith"); pstmt.setString(3, "January"); pstmt.setInt(4, 1000); pstmt.setString(5, "Hyderabad"); pstmt.addBatch(); pstmt.setString(1, "Earphones"); pstmt.setString(2, "Sumith"); pstmt.setString(3, "March"); pstmt.setInt(4, 500); pstmt.setString(5,"Vishakhapatnam"); pstmt.addBatch(); pstmt.setString(1, "Mouse"); pstmt.setString(2, "Sudha"); pstmt.setString(3, "September"); pstmt.setInt(4, 200); pstmt.setString(5, "Vijayawada"); pstmt.addBatch(); //Executing the batch pstmt.executeBatch(); //Saving the changes con.commit(); System.out.println("Records inserted......"); } }
輸出
Connection established...... Records inserted......
如果驗證Dispatches表的內容,您可以觀察到插入的記錄如下
+--------------+------------------+-------------------+-------+----------------+ | Product_Name | Name_Of_Customer | Month_Of_Dispatch | Price | Location | +--------------+------------------+-------------------+-------+----------------+ | KeyBoard | Amith | January | 1000 | Hyderabad | | Earphones | SUMITH | March | 500 | Vishakhapatnam | | Mouse | Sudha | September | 200 | Vijayawada | +--------------+------------------+-------------------+-------+----------------+
廣告