读取一个SQL文件 + 批量执行batchUpdate(String[ ])

来源:互联网 发布:linux shell % 编辑:程序博客网 时间:2024/06/16 20:38

  读取文件:先将文件转换为 InputStream流,然后再将流转为String

Thread.currentThread().getContextClassLoader().getResourceAsStream(resource)

  批量执行:

 

String content = FileUtil.readFile("com/enation/javashop/produceArea.sql");

 FileUtil.java:

public static String readFile(String resource) {InputStream stream = getResourceAsStream(resource);String content = readStreamToString(stream);return content;}
 
public static InputStream getResourceAsStream(String resource) {String stripped = resource.startsWith("/") ? resource.substring(1): resource;InputStream stream = null;ClassLoader classLoader = Thread.currentThread().getContextClassLoader();if (classLoader != null) {stream = classLoader.getResourceAsStream(stripped);}return stream;}
 
public static String readStreamToString(InputStream stream) {String fileContent = "";try {InputStreamReader read = new InputStreamReader(stream, "utf-8");BufferedReader reader = new BufferedReader(read);String line;while ((line = reader.readLine()) != null) {fileContent = fileContent + line + "\n";}read.close();read = null;reader.close();read = null;} catch (Exception ex) {fileContent = "";}return fileContent;}

 Game Over!

 

批量执行:

sql:

INSERT INTO `es_produce_area_<userid>_<siteid>` VALUES ('1', '0', ',0,', '1', '杭州市','1');INSERT INTO `es_produce_area_<userid>_<siteid>` VALUES ('2', '1', ',1,2,', '2', '上城区', '2');
 
String[] sql_ar = content.split(";\n");

 

 
jdbcTemplate.batchUpdate(sql_ar);
原创粉丝点击