您的位置:首页 > 数据库

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

2017-04-13 10:11 489 查看
  读取文件:先将文件转换为 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);






大小: 13.2 KB

查看图片附件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: