📄 usetran.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;
try {
// 通过连接池来获得一个连接
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/sqlserver");
con = ds.getConnection();
PreparedStatement updateAge = null;
String updateString = "update student "
+ "set age = ? where name like ?";
updateAge = con.prepareStatement(updateString);
int[] age = { 45, 39, 25, 96 };
String[] names = { "梁朝伟%", "贝壳汗母%", "小罗%", "霍元甲%" };
int len = age.length;
// 设置事务提交模式为非自动提交
con.setAutoCommit(false);
for (int i = 0; i < len; i++) {
updateAge.setInt(1, age[i]);
updateAge.setString(2, names[i]);
updateAge.executeUpdate();
}
// 上面执行的语句,如果不出现异常则提交 SQL 语句
con.commit();
out.println("<h1>修改成功,事务执行完毕</h1>");
} 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 + -