日期:2014-05-19  浏览次数:20674 次

批量插入问题
我的代码实现批量插入,虽然可以插入,我觉得写的不怎么好,有没有高手帮忙改下,或者有更好的方法,本人新手只想到这个方法,而且返回的count应该是有问题的
Java code

    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();
}



Java code

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;
        
    }



------解决方案--------------------
没序列,主键可能会重复!!。。。