運行環境:SpringBoot,注入JdbcTemplate
@Autowired private JdbcTemplate jdbcTemplate;
1、單表批量插入數據
@Test public void batchTest() throws IOException { InputStream inputStream = new FileInputStream("O:\\files\\測試.txt"); List<Object[]> list = new ArrayList<>(); for (String readLine : IOUtils.readLines(inputStream,"utf-8")){ String[] s = readLine.split("\\|"); //list.add(new Object[]{s[0],s[1],s[2],s[3],s[4]}); list.add(new Object[]{s[1],s[0]}); } //遍歷List<Object[]>集合中的每一個元素 /* for (Object[] o : list){ for (int i = 0; i < o.length; i++) { System.out.println("==========="+o[i]); } }*/ //執行批量插入操作 String sql = "INSERT INTO `test`(`name`,`area`) VALUES (?,?)"; jdbcTemplate.batchUpdate(sql, list); }
樣本數據:測試.txt
測試數據1|測試數據2|測試數據3
測試數據4|測試數據5|測試數據6
測試數據7|測試數據8|測試數據9
單次循環插入:
1 public void insertToTag(String filename) throws IOException { 2 InputStream is = new FileInputStream(filename); 3 4 Map<String,String> map = new HashMap<>(); 5 for (String readLine : IOUtils.readLines(is, "utf-8")) { 6 String[] s = readLine.split("\\|"); 7 map.put(s[1],s[0]); 8 } 9 10 String sql = "INSERT INTO `test`(`name`,`area`) VALUES (?,?)"; 11 for (Map.Entry<String, String> stringStringEntry : map.entrySet()) { 12 // System.out.println(stringStringEntry.getKey()+"-->"+stringStringEntry.getValue()); 13 jdbcTemplate.update(sql,stringStringEntry.getKey(),stringStringEntry.getValue()); 14 } 15 16 }
2、聯表插入數據,將字典表中的id插入到另一張表
1 public void insertToGuideBatch(String filename) throws IOException { 2 3 InputStream is = new FileInputStream(filename); 4 5 //字段名,id值 6 Map<String,Long> map1 = new HashMap<>(); 7 8 //該方法類似於set集合 9 SqlRowSet s1 = jdbcTemplate.queryForRowSet("SELECT `id`,`area` FROM g_enforcement_tag"); 10 while (s1.next()){ 11 map1.put(s1.getString("area"),s1.getLong("id")); 12 } 13 14 for (String readLine : IOUtils.readLines(is, "utf-8")) { 15 String[] s = readLine.split("\\|"); 16 Long id = map1.get(s[0]); 17 // jdbcTemplate.update("insert into xxx value (?,?)",id,s[4]); 18 jdbcTemplate.update("INSERT INTO `g_enforcement_guide`(`prop1`,`prop2`,`prop3`,`prop4`,`prop5`) VALUES (?,?,?,?,?)","test",id,s[2],s[3],s[4]); 19 20 } 21 }
