JSP应用JDBC实现数据库事务操作

//MySQL数据库中创建database account,表system1,system2.
create system1(name varchar(20),money double);
create system2(name varchar(20),money double);
insert into system1 values('dick',100000);
insert into system2 values('cll',5000);
//首先创建db6.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>db6.html</title>

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">

<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->

</head>

<body>
<center>
<p><b>银行转账系统</b></p>
<form action="db6.jsp" method="post">
请输入金额:
<input type="text" name="money" />
<input type="submit" value="提交" />
</form>
</center>
</body>
</html>

//创建db6.jsp

<%@ page language="java" import="java.util.*" pageEncoding="GB2312"%>
<%@page import="java.sql.*" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>数据库事务操作</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

</head>

<body>
<center>
<%
Connection con=null;
Statement stmt=null;
double money=Double.parseDouble(request.getParameter("money"));
String sql1="update system1 set money=money-"+money+"where name='dick'";
String sql2="update system2 set money=money+"+money+"where name='cll'";
String url="jdbc:mysql://localhost:3306/account?user=root&password=root&characterEncoding=gb2312";
try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection(url);//连接数据库
con.setAutoCommit(false); //禁止自动提交事务
stmt=con.createStatement();
stmt.executeUpdate(sql1); //没有自动提交sql语句
stmt.executeUpdate(sql2); //也没有自动提交sql语句
con.commit(); //统一提交事务
out.println("<center><b>转账成功</b></center>");
out.println("<center>本次转账金额为:"+money+"人民币</center>");
}catch(SQLException e){
//如果其中一项SQL操作失败,就不会执行commit()方法,而是产生相应的sqlexception,
//此时就可以捕获异常代码块中调用rollback()方法撤销事务
con.rollback();
out.print("转账失败,原因:"+e.toString());
}finally{
if(stmt!=null){
stmt.close();
}
if(con!=null){
con.close();
}
}
%>
</center>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值