在《【数据批处理1】动态增删表单节点》一文中我们介绍了前台如何动态增删节点并传递参数及节点数量到后台。
本文将介绍后台如何对前台传入的参数进行批量的获取及批量提交,及如何使用JDBC的批处理功能达到数据批量提交的目的。
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设定字符集
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
//获取条目数量
String itemSize = request.getParameter("hidden");
System.out.println(itemSize);
int size = Integer.valueOf(itemSize);
String [] usernames = new String[size];
String [] userpwds = new String[size];
//获取参数
usernames = request.getParameterValues("name");
userpwds = request.getParameterValues("passwd");
//非空则提交
if (usernames.length == 0 || usernames == null || userpwds.length == 0 || userpwds == null || usernames[0] == "" || userpwds[0] == "") {
request.setAttribute("msg", "参数无效或有错");
} else {
Map<String, String[]> params = new HashMap<>();
params.put("usernames", usernames);
params.put("userpwds", userpwds);
TestDao testDao = new TestDao();
//添加成功条数
int flag = testDao.commitInsert(params);
System.out.println(size);
if (flag > 0) {
request.setAttribute("msg", "提交成功");
}
}
request.getRequestDispatcher("/WEB-INF/index.jsp").forward(request, response);
}
public int commitInsert(Map<String, String[]> params) {
String [] usernames = params.get("usernames");
String [] userpwds = params.get("userpwds");
//获取连接
try {
String sql = " insert into test(name, passwd) values(?,?) ";
connection = JDBCTools.getConnection();
connection.setAutoCommit(false);
PreparedStatement pstmt = connection.prepareStatement(sql);
for (int i = 0; i < userpwds.length; i++) {
pstmt.setString(1, usernames[i]);
pstmt.setString(2, userpwds[i]);
pstmt.addBatch();
}
results = pstmt.executeBatch();
connection.commit();
} catch (Exception e) {
e.printStackTrace();
}
return results.length;
}