<SQL:事务>标记用于组的<SQL:查询>和<SQL:更新>标签进入事务。您可以在<sql:transaction>标记内放置尽可能多的<sql:query>和<sql:update>标记作为语句,以创建单个事务。
如果任何嵌套操作引发异常,它可以确保由嵌套操作执行的数据库修改被提交或回滚。
<SQL:事务>标签具有以下属性-
属性 | 描述 | 需要 | 默认 |
---|---|---|---|
数据源 | 要使用的数据库连接(覆盖默认值) | 没有 | 默认数据库 |
隔离 | 事务隔离(READ_COMMITTED,READ_UNCOMMITTED,REPEATABLE_READ或SERIALIZABLE) | 没有 | 数据库的默认值 |
首先介绍基本概念,让我们在TEST数据库中创建一个Student表,并在该表中创建一些记录,如下所示-
打开命令提示符,然后更改为安装目录,如下所示:
C:\> C:\>cd Program Files\MySQL\bin C:\Program Files\MySQL\bin>
登录数据库,如下所示:
C:\Program Files\MySQL\bin>mysql -u root -p Enter password: ******** mysql>
在TEST数据库中创建Employee表,如下所示-
mysql> use TEST; mysql> create table Students ( id int not null, first varchar (255), last varchar (255), dob date ); mysql>
现在,我们将在Employee表中创建一些记录,如下所示:
mysql> INSERT INTO Students VALUES (100, 'Zara', 'Ali', '2002/05/16'); mysql> INSERT INTO Students VALUES (101, 'Mahnaz', 'Fatma', '1978/11/28'); mysql> INSERT INTO Students VALUES (102, 'Zaid', 'Khan', '1980/10/10'); mysql> INSERT INTO Students VALUES (103, 'Sumit', 'Mittal', '1971/05/08'); mysql>
现在让我们编写一个JSP,它将使用<sql:update>标记和 <sql:transaction>标记一起执行SQL UPDATE语句。这里<sql:transaction>标记内的代码将完全执行或根本不执行-
<%@ page import = "java.io.*,java.util.*,java.sql.*"%> <%@ page import = "javax.servlet.http.*,javax.servlet.*"%> <%@ page import = "java.util.Date,java.text.*" %> <%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c"%> <%@ taglib uri = "http://java.sun.com/jsp/jstl/sql" prefix = "sql"%> <html> <head> <title>JSTL sql:transaction Tag</title> </head> <body> <sql:setDataSource var = "snapshot" driver = "com.mysql.jdbc.Driver" url = "jdbc:mysql://localhost/TEST" user = "root" password = "cohondob"/> <% Date DoB = new Date("2001/12/16"); int studentId = 100; %> <sql:transaction dataSource = "${snapshot}"> <sql:update var = "count"> UPDATE Students SET last = 'Ali' WHERE Id = 102 </sql:update> <sql:update var = "count"> UPDATE Students SET last = 'Shah' WHERE Id = 103 </sql:update> <sql:update var = "count"> INSERT INTO Students VALUES (104,'Nuha', 'Ali', '2010/05/26'); </sql:update> </sql:transaction> <sql:query dataSource = "${snapshot}" var = "result"> SELECT * from Students; </sql:query> <table border = "1" width = "100%"> <tr> <th>Emp ID</th> <th>First Name</th> <th>Last Name</th> <th>DoB</th> </tr> <c:forEach var = "row" items = "${result.rows}"> <tr> <td> <c:out value = "${row.id}"/></td> <td> <c:out value = "${row.first}"/></td> <td> <c:out value = "${row.last}"/></td> <td> <c:out value = "${row.dob}"/></td> </tr> </c:forEach> </table> </body> </html>
访问上面的JSP,将显示以下结果-
+-------------+----------------+-----------------+-----------------+ | Emp ID | First Name | Last Name | DoB | +-------------+----------------+-----------------+-----------------+ | 100 | Zara | Ali | 2001-12-16 | | 101 | Mahnaz | Fatma | 1978-11-28 | | 102 | Zaid | Ali | 1980-10-10 | | 103 | Sumit | Mittal | 1971-05-08 | | 104 | Nuha | Ali | 2010-05-26 | +-------------+----------------+-----------------+-----------------+