讀取txt文件然後錄入數據庫(批處理)

public static void main(String[] args) {
    File file = new File("1.txt");
    txt2String(file);
}
    
    public static String txt2String(File file){
        StringBuilder result = new StringBuilder();
        int i=0;
        try{
    JT_po[] sql3 = new JT_po[20000];
            BufferedReader br = new BufferedReader(new FileReader(file));//構造一個BufferedReader類來讀取文件
            String s = null;
            while((s = br.readLine())!=null){//使用readLine方法,一次讀一行
            JT_po jt_po=new JT_po();
            int nu=s.lastIndexOf("#");
            String[] dd= s.split("#");
            jt_po.setAllcount( s.substring((nu+1),s.length()));
            jt_po.setId(dd[0].toString());
            jt_po.setNewstext("0");
            jt_po.setNewstime(dd[4].toString());
            jt_po.setTitle(dd[3].toString());
            jt_po.setType1(dd[1].toString());
            jt_po.setType2(dd[2].toString());
                result.append(System.lineSeparator()+s);
                sql3[i]=jt_po;
                i++;
            }
            DBService.insert(sql3);
            br.close();    
        }catch(Exception e){
            e.printStackTrace();
        }

        return result.toString();

    }




DBService     採用的spring的數據庫操作


//測試專有
 public static int insert(final JT_po[] sqlArray) throws Exception {  
 String  sql="insert into D_SRC_FLOW(MC,TYPE1,TYPE2,TYPE3,Ldbh,Lnglat,Type) values(?,?,?,?,?,?,?)";
       try{    
        JdbcTemplate  jdbcTemplate = jdbcTemplateMap.get(YJZHDEVICE);
           int[] ii =jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter(){  
                public void setValues(PreparedStatement ps, int i)    
                   throws SQLException {    
                  JT_po jt= sqlArray[i];
               ps.setString(1,jt.getId());  
               ps.setString(2,jt.getType1());  
               ps.setString(3,jt.getType2());  
               ps.setString(4,jt.getTitle());  
               ps.setString(5,jt.getNewstime());  
               ps.setString(6,jt.getAllcount());  
               ps.setString(7,jt.getNewstext());  
           }  
               @Override  
               public int getBatchSize() {  
                   return sqlArray.length;
               }    
           });    
           System.out.println("sql執行完成,長度爲:"+ii.length);
           return ii.length;  
       }catch (org.springframework.dao.DataAccessException e) {    
           e.printStackTrace();    
       }  
       return 0;   
   }  

發佈了34 篇原創文章 · 獲贊 26 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章