一个JDBC实现批量删除的例子

数据库:SQLServer2005
服务器:Tomcat6.0
开发工具:MyEclipse6.0
采用框架:Struts1.2

贴出完整代码 :

创建SQL脚本:
CREATE TABLE [dbo].[batch](
 [id] [int] IDENTITY(1,1) NOT NULL,
 [name] [varchar](50) NULL,
 [password] [varchar](50) NULL,
 CONSTRAINT [PK_batch] PRIMARY KEY CLUSTERED
(
 [id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

连接数据库类:
public class DBConnection {
 private static DBConnection dbc = null;

 public static Connection getDBConnection() throws Exception {
  if (dbc == null) {
   dbc = new DBConnection();
  }
  return dbc._getConnection();
 }

 public Connection _getConnection() throws Exception {
  Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
  return DriverManager.getConnection(
    "jdbc:sqlserver://localhost:1433;DatabaseName=dbtest", "sa",
    "sqlserver2005");
 }
}

采用DAO工厂模式:

PO类:
public class Batch {
 private int id;
 private String name;
 private String password;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }
}

DAO接口:

public interface BatchDAO {
 public List<Batch> queryAll();

 public void deleteSelect(int[] str);
}

实现接口类:

public class BatchDAOImpl implements BatchDAO {
 Connection con = null;
 PreparedStatement pst = null;
 ResultSet rst = null;

 public void deleteSelect(int[] str) {
  String sql = "delete from batch where id in(";
  if(str.length==1){
   sql=sql+str[0]+")";}else{
    for(int i=0;i<str.length;i++){
     if(i==0){
      sql=sql+str[0];
     }
     else if(i==str.length-1){
      sql=sql+","+str[i]+")";
     }else{
      sql=sql+","+str[i];
     }
    }
   }
  try {
   con = DBConnection.getDBConnection();
   pst = con.prepareStatement(sql);
   pst.execute();
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   try {
    if (pst != null)
     pst.close();
    if (con != null)
     con.close();
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
 }

 public List<Batch> queryAll() {
  List<Batch> list = new ArrayList<Batch>();
  String sql = "select * from batch";
  try {
   con = DBConnection.getDBConnection();
   pst = con.prepareStatement(sql);
   rst = pst.executeQuery();
   while (rst.next()) {
    Batch b = new Batch();
    b.setId(rst.getInt("id"));
    b.setName(rst.getString("name"));
    b.setPassword(rst.getString("password"));
    list.add(b);
   }
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   try {
    if (rst != null)
     rst.close();
    if (pst != null)
     pst.close();
    if (con != null)
     con.close();
   } catch (SQLException e) {
    e.printStackTrace();
   }
  }
  return list;
 }
}

工厂类:

public class DAOFactory {
 public static BatchDAO getBatchDAOImplInstance() {
  return new BatchDAOImpl();
 }
}

Action:继承DispatchAction

public class BatchAction extends DispatchAction {
 /*
  * Generated Methods
  */

 /**
  * Method execute
  *
  * @param mapping
  * @param form
  * @param request
  * @param response
  * @return ActionForward
  */
 public ActionForward queryAll(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response) {
  List<Batch> list = DAOFactory.getBatchDAOImplInstance().queryAll();
  request.setAttribute("list", list);
  return mapping.findForward("display");
 }

 public ActionForward deleteSelect(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response) {
  String[] id = request.getParameterValues("name");
  int[] i = new int[id.length];
  for (int j = 0; j < id.length; j++) {
   i[j] = Integer.parseInt(id[j]);
  }
  DAOFactory.getBatchDAOImplInstance().deleteSelect(i);
  return mapping.findForward("delete");
 }
}
struts-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">

<struts-config>
  <data-sources />
  <form-beans />
  <global-exceptions />
  <global-forwards />
  <action-mappings >
    <action
      input="/index.jsp"
      parameter="batch"
      path="/batch"
      type="com.batch.delete.struts.action.BatchAction"
      validate="false">
      <forward name="display" path="/batchList.jsp" />
      <forward name="delete" path="/batchList.jsp" />
    </action>

  </action-mappings>

  <message-resources parameter="com.batch.delete.struts.ApplicationResources" />
</struts-config>

以下是页面内容:

<%@ page contentType="text/html;charset=GBK"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
  <title>batch_delete</title>
 </head>
 <script type="text/javascript" src="js/check.js"></script>
 <body>
  <center>
   <h2>
    Batch Delete Database Data Sample Display
   </h2>
   <hr>
   <form action="batch.do?batch=deleteSelect" name="myForm"
    method="post">
    <table style="border-collapse: collapse" border="1"
     bordercolor="#1E90FF" height="60" cellpadding="3">
     <tr style="background: #87CEFA;">
      <td>
       &nbsp;
      </td>
      <td>
       ID
      </td>
      <td>
       Name
      </td>
      <td>
       Password
      </td>
     </tr>
     <logic:iterate id="li" name="list">
      <tr>
       <td>
        <input type="checkbox" name="name" value="${li.id }">
       </td>
       <td>
        ${li.id }
       </td>
       <td>
        ${li.name }
       </td>
       <td>
        ${li.password }
       </td>
      </tr>
     </logic:iterate>
     <tr>
      <td colspan="4">
       <input type="button" value="SelectAll" onclick="checkAll()">
       &nbsp;
       <input type="submit" value="DeleteSelect">
       &nbsp;
       <input type="reset" value="ResetSelect">
      </td>
     </tr>
    </table>
   </form>
  </center>
 </body>
</html>

JSP页面引入一个js文件:

function checkAll() {
 for (var i = 0; i < myForm.name.length; i++) {
  myForm.name[i].checked=true;
 }
}

你可能感兴趣的:(apache,sql,jsp,jdbc,struts)