日期:2014-05-19 浏览次数:20754 次
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name=request.getParameter("name"); //String[] vallists=request.getParameterValues("vallist"); name="testnettype"; String[] vallists= {"1,2","2,3","3,4"}; String pcount=vallists[1]; String[] szcount=pcount.split(","); int counts=szcount.length; Dao dao=new Dao(); int count=0; PrintWriter out = null; try { response.setContentType("text/plain; charset=UTF-8"); out=response.getWriter(); count = dao.Batch(vallists, name,counts); out.println(count); } catch (Exception e) { StringWriter sw=new StringWriter(); e.printStackTrace(new PrintWriter(sw)); System.out.println(sw.toString()); out.println(0); } out.flush(); out.close(); }
public int Batch(String[] list,String tablename,int counts){ Connection conn = null; PreparedStatement pst = null; int count=0; String values=""; try { conn = ConnectionSource.getConnection(); for (int i = 0; i < counts; i++) { values+="?,"; } String value=values.substring(0, values.length()-1); String sql="insert into "+tablename +" values("+value+")"; pst = conn.prepareStatement(sql); conn.setAutoCommit(false); for (int i = 0; i < list.length; i++) { String pcount=list[i]; String[] szcount=pcount.split(","); for (int j = 0; j <szcount.length; j++) { pst.setObject(j+1, szcount[j]); } pst.addBatch(); count++;//用于记录插入多少,但是如果回滚了这个还是在的!!!! } pst.executeBatch(); conn.commit(); } catch (SQLException e) { if(conn != null){ try { conn.rollback(); conn.commit(); } catch (SQLException e1) { loggerError.error(e1); e1.printStackTrace(); } } loggerError.error(e); e.printStackTrace(); } finally { ConnectionSource.releaseSource(null, pst, conn); } return count; }