📄 batchupdate_test.jsp
字号:
<%@ page language="java" contentType="text/html; charset=GBK"%>
<%@ page import="java.sql.*,javax.naming.*,javax.sql.*" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>使用数据库批处理更新</title>
</head>
<body>
<%
Connection con = null;
Statement stmt = null;
try {
// 通过连接池来获得一个连接
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/sqlserver");
con = ds.getConnection();
stmt = con.createStatement();
con.setAutoCommit(false);
stmt.addBatch("insert into student values(20,'拉登',56)");
stmt.addBatch("insert into student values(21,'张学友',49)");
stmt.addBatch("insert into student values(22,'刘德华',51)");
stmt.addBatch("insert into student values(23,'猪八戒',128)");
int[] updateCounts = stmt.executeBatch();
con.commit();
for (int i = 0; i < updateCounts.length; i++) {
out.println("第" + (i + 1) + "条SQL语句修改数据库记录数 : "
+ updateCounts[i]+"<br>");
}
con.setAutoCommit(true);
ResultSet uprs = stmt.executeQuery("select * from student");
out.println("执行批处理更新后的student表中记录:<br>");
while (uprs.next()) {
String name = uprs.getString("name");
int age = uprs.getInt("age");
out.print(name + " " + age+"<br>");
out.println();
}
// 上面执行的语句,如果不出现异常则提交 SQL 语句
con.commit();
out.println("<h1>修改成功,事务执行完毕</h1>");
uprs.close();
stmt.close();
} catch (NamingException ex) {
System.out.println("Name Not Bound : " + ex.getMessage());
} catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
if (con != null) {
try {
System.out.print("Transaction is being ");
System.out.println("rolled back");
// 如果出现异常则事务回滚
con.rollback();
} catch (SQLException excep) {
System.out.print("SQLException: ");
System.out.println(excep.getMessage());
}
}
} finally {// 不管发生不发生异常,要关闭连接,释放资源
try {
if (con != null) {
con.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
%>
</body>
</html>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -