avaweb对数据库进行事务处理(批量删除操作)

简介:
文是记录Java对数据库进行事务处理(删除操作),在开始之前先来看下面这样的一个页面图:

                上面这张图片显示的是从数据库中查询出的用户信息,信息中进行了分页处理,然后每行的前面提供了一个复选按钮,可以选中多个进行操作,这里主要是进行删除操作。在执行删除操作之前先先要选中对应的行信息,点击删除进行删除。当进行多条信息删除的时候,需要使用java的事务处理机制对数据库进行删除,也就是说删除的时候如果选中的要删除的说有信息其中一条没有成功删除的话,那么就都不删除。
                他们就像加盟了某个组织,他们都很讲义气,要死他们一起死,要活一起活,谁也不会落下。现在是在java中要对数据库实现这一操作,我们可看下面的代码,它实现了对数据库的批量删除操作,并且同生死,代码如下:
[java] view plaincopy
/** 
         * 根据用户代码进行批量删除 
         * @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;    
        }    
当然上面是进行批量删除,如果我们只删除一条信息的话也可以使用单独的删除方法,当然上面的方法也是可以完成的,管他的,还是再看一下吧:
[java] view plaincopy
/** 
         * 根据用户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;    
        }    
上面是对数据库的操作代码,下面看一下页面中怎样实现的,代码如下:
[html] view plaincopy
<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">    
                                                Email    
                                        </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></pre>    
<pre></pre>    
<p></p>    
<p>上面只是给出数据库删除操作的那一部分java代码,如果需要看看数据库连接以及分页的实现的话可以看前面写过的几篇文章,里面有详细的代码说明的。</p>    

<pre></pre>    


















本文转自yunlielai51CTO博客,原文链接:http://blog.51cto.com/4925054/1156950,如需转载请自行联系原作者


相关文章
ly~
|
2月前
|
数据库 数据库管理
数据库的事务处理机制有哪些优点?
数据库的事务处理机制具备多种优势:首先,它能确保数据一致性,通过原子性保证所有操作全成功或全失败,利用完整性约束维护数据的有效性;其次,增强了系统可靠性,提供故障恢复能力和正确处理并发操作的功能;最后,简化了应用程序开发工作,将操作封装为逻辑单元并集中处理错误,降低了开发复杂度。
ly~
48 1
|
4月前
|
SQL 数据处理 数据库
SQL进阶之路:深入解析数据更新与删除技巧——掌握批量操作、条件筛选、子查询和事务处理,提升数据库维护效率与准确性
【8月更文挑战第31天】在数据库管理和应用开发中,数据的更新和删除至关重要,直接影响数据准确性、一致性和性能。本文通过具体案例,深入解析SQL中的高级更新(UPDATE)和删除(DELETE)技巧,包括批量更新、基于条件的删除以及使用子查询和事务处理复杂场景等,帮助读者提升数据处理能力。掌握这些技巧能够有效提高数据库性能并确保数据一致性。
97 0
|
5月前
|
Oracle 关系型数据库 Java
实时计算 Flink版操作报错合集之cdc postgres数据库,当表行记录修改后报错,该如何修改
在使用实时计算Flink版过程中,可能会遇到各种错误,了解这些错误的原因及解决方法对于高效排错至关重要。针对具体问题,查看Flink的日志是关键,它们通常会提供更详细的错误信息和堆栈跟踪,有助于定位问题。此外,Flink社区文档和官方论坛也是寻求帮助的好去处。以下是一些常见的操作报错及其可能的原因与解决策略。
|
5月前
|
SQL 监控 关系型数据库
实时计算 Flink版操作报错合集之在设置监控PostgreSQL数据库时,将wal_level设置为logical,出现一些表更新和删除操作报错,怎么办
在使用实时计算Flink版过程中,可能会遇到各种错误,了解这些错误的原因及解决方法对于高效排错至关重要。针对具体问题,查看Flink的日志是关键,它们通常会提供更详细的错误信息和堆栈跟踪,有助于定位问题。此外,Flink社区文档和官方论坛也是寻求帮助的好去处。以下是一些常见的操作报错及其可能的原因与解决策略。
|
5月前
|
关系型数据库 Java 数据库
实时计算 Flink版操作报错合集之flinksql采PG数据库时报错,该如何解决
在使用实时计算Flink版过程中,可能会遇到各种错误,了解这些错误的原因及解决方法对于高效排错至关重要。针对具体问题,查看Flink的日志是关键,它们通常会提供更详细的错误信息和堆栈跟踪,有助于定位问题。此外,Flink社区文档和官方论坛也是寻求帮助的好去处。以下是一些常见的操作报错及其可能的原因与解决策略。
|
5月前
|
关系型数据库 MySQL 数据库
实时计算 Flink版操作报错合集之在处理PostgreSQL数据库遇到报错。该如何解决
在使用实时计算Flink版过程中,可能会遇到各种错误,了解这些错误的原因及解决方法对于高效排错至关重要。针对具体问题,查看Flink的日志是关键,它们通常会提供更详细的错误信息和堆栈跟踪,有助于定位问题。此外,Flink社区文档和官方论坛也是寻求帮助的好去处。以下是一些常见的操作报错及其可能的原因与解决策略。
|
5月前
|
消息中间件 关系型数据库 数据库
实时计算 Flink版操作报错合集之在使用RDS数据库作为源端,遇到只能同步21个任务,是什么导致的
在使用实时计算Flink版过程中,可能会遇到各种错误,了解这些错误的原因及解决方法对于高效排错至关重要。针对具体问题,查看Flink的日志是关键,它们通常会提供更详细的错误信息和堆栈跟踪,有助于定位问题。此外,Flink社区文档和官方论坛也是寻求帮助的好去处。以下是一些常见的操作报错及其可能的原因与解决策略。
|
5月前
|
SQL 数据库 Python
Django框架数据库ORM查询操作(6)
【7月更文挑战第6天】```markdown Django ORM常用数据库操作:1) 查询所有数据2) 根据ID查询 3) 精确查询 4) 分页排序
84 1
|
5月前
|
存储 监控 安全
安全规范问题之跟数据库交互涉及的敏感数据操作需要有哪些措施
安全规范问题之跟数据库交互涉及的敏感数据操作需要有哪些措施
|
5月前
|
分布式计算 DataWorks Java
DataWorks操作报错合集之无法连接到指定的数据库实例,该如何解决
DataWorks是阿里云提供的一站式大数据开发与治理平台,支持数据集成、数据开发、数据服务、数据质量管理、数据安全管理等全流程数据处理。在使用DataWorks过程中,可能会遇到各种操作报错。以下是一些常见的报错情况及其可能的原因和解决方法。