本文是记录Java对数据库进行事务处理(删除操作),在开始之前先来看下面这样的一个页面图:
上面这张图片显示的是从数据库中查询出的用户信息,信息中进行了分页处理,然后每行的前面提供了一个复选按钮,可以选中多个进行操作,这里主要是进行删除操作。在执行删除操作之前先先要选中对应的行信息,点击删除进行删除。当进行多条信息删除的时候,需要使用java的事务处理机制对数据库进行删除,也就是说删除的时候如果选中的要删除的说有信息其中一条没有成功删除的话,那么就都不删除。
他们就像加盟了某个组织,他们都很讲义气,要死他们一起死,要活一起活,谁也不会落下。现在是在java中要对数据库实现这一操作,我们可看下面的代码,它实现了对数据库的批量删除操作,并且同生死,代码如下:
/**当然上面是进行批量删除,如果我们只删除一条信息的话也可以使用单独的删除方法,当然上面的方法也是可以完成的,管他的,还是再看一下吧:
* 根据用户代码进行批量删除
* @param userIds
* @return
*/
public boolean delUsers(String[] userIds){
boolean flag = false;
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "delete from t_user where user_id=?";
try {
conn = DbUtil.getConnection();
conn.setAutoCommit(false);
pstmt = conn.prepareStatement(sql);
for(int i =0 ;i<userIds.length;i++){
pstmt.setString(1,userIds[i].trim());
pstmt.addBatch();
}
pstmt.executeBatch(); //批量执行
conn.commit();//提交事务
flag = true;
} catch (SQLException e) {
try {
conn.rollback(); //进行事务回滚
} catch (SQLException ex) {
}
}finally {
DbUtil.close(pstmt);
DbUtil.close(conn);
}
return flag;
}
/**上面是对数据库的操作代码,下面看一下页面中怎样实现的,代码如下:
* 根据用户id进行删除单条信息
* @param userId
* @return
*/
public boolean delUser(String userId){
boolean flag = false;
String sql = "delete from t_user where user_id=?";
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = DbUtil.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, userId);
if(pstmt.executeUpdate()>0){
flag = true;
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
DbUtil.close(pstmt);
DbUtil.close(conn);
}
return flag;
}
<pre name="code" class="java"><%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="org.ml.drp.sysmgr.domain.*"%>
<%@ page import="org.ml.drp.sysmgr.manager.*" %>
<%@ page import="org.ml.drp.util.*"%>
<%@ page import="java.util.*"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
//进行用户信息的删除
String command = request.getParameter("command");
if ("del".equals(command)) {
String[] userIds = request.getParameterValues("selectFlag");
boolean flag = false;
if(userIds.length==1){
flag = UserManager.getInstance().delUser(userIds[0]);
}else{
flag = UserManager.getInstance().delUsers(userIds);
}
if(flag){
out.print("<script>alert('删除成功!');</script>");
}else{
out.print("<script>alert('删除失败!');</script>");
}
}
//下面为分页显示做准备
String currentPageStr = request.getParameter("currentPage");
String pageSizeStr = request.getParameter("pageSize");
int currentPage = 1; //当前页码
int pageSize = 8 ;//每页显示数量
if(currentPageStr!=null){
currentPage = Integer.parseInt(currentPageStr);
}
if(pageSizeStr!=null){
pageSize = Integer.parseInt(pageSizeStr);
}
Page<User> p = UserManager.getInstance().findByPage(currentPage,pageSize);
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户维护</title>
<link rel="stylesheet" href="../style/drp.css">
<script src="../script/client_validate.js"></script>
<script type="text/javascript">
function addUser() {
window.self.location = "user_add.jsp";
}
function modifyUser() {
var select = document.getElementsByName("selectFlag");
var userName = document.getElementsByName("userName");
var password = document.getElementsByName("password");
var contactTel = document.getElementsByName("contactTel");
var email = document.getElementsByName("email");
var count = 0;
var k = 0;
for(var i = 0;i<select.length;i++){
if(select[i].checked){
count++;
k = i;
}
}
if(count==0){
alert("请先选择要修改的记录");
}else if(count > 1){
alert("对不起,每次只能修改一条记录,请重新选择!");
}else if(count==1){
window.self.location = "user_modify.jsp?userId="+select[k].value+"&userName="+encodeURI(encodeURI(userName[k].value))+"&password="+password[k].value+"&contactTel="+contactTel[k].value+"&email="+email[k].value;
}
}
//删除用户控制
function deleteUser() {
var select = document.getElementsByName("selectFlag");
var flag = false;
for (var i=0; i<select.length; i++) {
if (select[i].checked) {
flag = true;
break;
}
}
if (!flag) {
alert("请选择需要删除的用户!");
return;
}
if (window.confirm("确认删除吗?")) {
with (document.getElementById("userform")) {
action="user_maint.jsp?command=del";
method="post";
submit();
}
}
}
//全选/反选操作
function checkAll(ifAll) {
var select = document.getElementsByName("selectFlag");
for(var i = 0;i<select.length;i++){
select[i].checked = ifAll.checked;
}
}
function topPage(num) {
document.getElementById("currentPage").value = num ;
document.userform.submit() ; // 表单提交
}
function previousPage(num) {
document.getElementById("currentPage").value = num ;
document.userform.submit() ; // 表单提交
}
function nextPage(num) {
document.getElementById("currentPage").value = num ;
document.userform.submit() ; // 表单提交
}
function bottomPage(num) {
document.getElementById("currentPage").value = num ;
document.userform.submit() ; // 表单提交
}
</script>
</head>
<body class="body1">
<form name="userform" id="userform">
<div>
<table width="95%" border="0" cellspacing="0" cellpadding="0"
height="35" >
<tr>
<td class="p1" height="18" nowrap>
</td>
</tr>
<tr>
<td width="522" class="p1" height="17" nowrap>
<img src="../images/mark_arrow_02.gif" width="14" height="14">
<b>系统管理>>用户维护</b>
</td>
</tr>
</table>
<hr width="100%" align="center" size=0>
</div>
<table width="95%" height="20" border="0" align="center"
cellspacing="0" id="toolbar" style="height: 25;background-color: #696969">
<tr>
<td width="49%" class="rd19">
<font color="#0033FF">查询列表</font>
</td>
<td width="27%" nowrap class="rd16">
<div align="right"></div>
</td>
</tr>
</table>
<table width="95%" border="1" cellspacing="0" cellpadding="0"
align="center" class="table1">
<tr height="50px">
<td width="50" class="rd6">
<label>
<input type="checkbox" name="ifAll" title="全选/反选" id="ifAll" onClick="checkAll(this)">
</label>
</td>
<td width="119" class="rd6" >
用户代码
</td>
<td width="152" class="rd6">
用户名称
</td>
<td width="152" class="rd6">
密码
</td>
<td width="166" class="rd6">
联系电话
</td>
<td width="150" class="rd6">
</td>
<td width="153" class="rd6">
创建日期
</td>
</tr>
<%
List<User> userList = p.getList();
Iterator<User> iter = userList.iterator();
while(iter.hasNext()){
User user = (User)iter.next();
%>
<tr>
<td class="rd8" >
<label>
<input type="checkbox" name="selectFlag" class="checkbox1" value="<%=user.getUserId() %>">
</label>
</td>
<td class="rd8">
<%=user.getUserId() %>
<input type="hidden" value="<%=user.getUserId() %>" name="userId">
</td>
<td class="rd8">
<%=user.getUserName() %>
<input type="hidden" value="<%=user.getUserName() %>" name="userName">
</td>
<td class="rd8">
<%=user.getPassword() %>
<input type="hidden" value="<%=user.getPassword() %>" name="password">
</td>
<td class="rd8">
<%=user.getContactTel() %>
<input type="hidden" value="<%=user.getContactTel() %>" name="contactTel">
</td>
<td class="rd8">
<%=user.getEmail() %>
<input type="hidden" value="<%=user.getEmail() %>" name="email">
</td>
<td class="rd8">
<%=user.getCreateDate() %>
<input type="hidden" value="<%=user.getCreateDate() %>" name="userId">
</td>
</tr>
<%
}
%>
</table>
<table width="95%" height="30" border="0" align="center"
cellpadding="0" cellspacing="0" style="height: 25;background-color: #696969">
<tr>
<td nowrap class="rd19" height="2">
<div align="left">
<font color="#0033FF"> 共</font>
<font color="#FF0000"> <%=p.getPageCount() %></font>
<font color="#0033FF">页</font>
<font color="#0033FF">当前第</font>
<font color="#FF0000"><%=p.getCurrentPage() %></font>
<font color="#0033FF">页</font>
</div>
</td>
<td nowrap class="rd19">
<div align="right">
<input name="btnTopPage" class="button1" type="button"
id="btnTopPage" value="|<< " title="首页"
onClick="topPage(<%=1 %>)"<%=currentPage==1?"DISABLED":""%>>
<input name="btnPreviousPage" class="button1" type="button"
id="btnPreviousPage" value=" < " title="上页"
onClick="previousPage(<%=currentPage-1 %>)" <%=currentPage==1?"DISABLED":""%>>
<input name="btnNextPage" class="button1" type="button"
id="btnNextPage" value=" > " title="下页" onClick="nextPage(<%=currentPage+1 %>)" <%=currentPage==p.getPageCount()?"DISABLED":""%>>
<input name="btnBottomPage" class="button1" type="button"
id="btnBottomPage" value=" >>|" title="尾页"
onClick="bottomPage(<%=p.getPageCount() %>)"<%=currentPage==p.getPageCount()?"DISABLED":""%>>
<input name="btnAdd" type="button" class="button1" id="btnAdd"
value="添加" onClick="addUser()">
<input name="btnDelete" class="button1" type="button"
id="btnDelete" value="删除" onClick="deleteUser()">
<input name="btnModify" class="button1" type="button"
id="btnModify" value="修改" onClick="modifyUser()">
</div>
</td>
</tr>
</table>
<p>
<input type="hidden" name="currentPage" id="currentPage" value="1">
</p>
</form>
</body>
上面只是给出数据库删除操作的那一部分java代码,如果需要看看数据库连接以及分页的实现的话可以看前面写过的几篇文章,里面有详细的代码说明的。