executeBatch()方法用於成批地執行SQL語句,但不能執行返回值是ResultSet結果集的SQL語句,而是直接執行stmt.executeBatch();
輔助方法:
addBatch();向批處理中加入一個更新語句。
clearBatch():清空批處理中的更新語句
testExecuteBatch.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <%@page import="java.sql.*" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'executeBatch.jsp' starting page</title> </head> <body> <% String url="jdbc:mysql://localhost:3306/student?useSSL=true"; String useName="root"; String password="2277092"; Connection conn=null; Statement stmt=null; try{ Class.forName("com.mysql.jdbc.Driver"); //out.print("加載驅動類成功"); } catch(Exception e){ out.print(e); } try{ conn=DriverManager.getConnection(url,useName,password); stmt=conn.createStatement(); //使用addBatch()添加SQL語句 stmt.addBatch("insert into classinfo values(4,'石蘭','女','網絡工程','2277092','五邑大學','20','90');"); stmt.addBatch("update classinfo set phone='18814182472' where no=3113002421"); //使用executeBatch()執行批量更新語句 stmt.executeBatch(); //統計更新計數數組 /* int affectRowCounts[]=stmt.executeBatch(); for(int i=0;i<affectRowCounts.length;i++){ out.print("第"+(i+1)+"個更新語句影響的數據行數為:"+affectRowCounts[i]+"<br>"); } */ stmt.close(); out.print("更新成功"); } catch(SQLException e){ out.print(e); } finally{ try{ if(conn!=null) conn.close(); } catch(SQLException e){ out.print("關閉數據庫連接出現異常"); } } %> </body> </html>
