java执行sql脚本,一种是解析sql脚本,生成每一条sql语句,由java jdbc去执行。
第二种是利用 Ant 的SQL Task来实现执行SQL 脚本的功能。[url]http://daoshud1.iteye.com/blog/1913149[/url]
第二种是利用 Ant 的SQL Task来实现执行SQL 脚本的功能。[url]http://daoshud1.iteye.com/blog/1913149[/url]
public static void main(String[] args) {
try {
List<String> sqlList = new sqlUtil().loadSql("g:\\menuinfo-sql-data.sql");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
*
* @Title: loadSql
* @Description: TODO(解析sql)
* @param @param sqlFile
* @param @return
* @param @throws Exception 设定文件
* @return List<String> 返回类型
* @throws
*/
private List<String> loadSql(String sqlFile) throws Exception {
List<String> sqlList = new ArrayList<String>();
try {
InputStream sqlFileIn = new FileInputStream(sqlFile);
StringBuffer sqlSb = new StringBuffer();
byte[] buff = new byte[1024];
int byteRead = 0;
while ((byteRead = sqlFileIn.read(buff)) != -1) {
sqlSb.append(new String(buff, 0, byteRead,"utf-8"));//防止中文乱码
}
// Windows 下换行是 \r\n, Linux 下是 \n
String[] sqlArr = sqlSb.toString()
.split("(;\\s*\\r\\n)|(;\\s*\\n)");
for (int i = 0; i < sqlArr.length; i++) {
String sql = sqlArr[i].replaceAll("--.*", "").trim();
if (!sql.equals("")) {
sqlList.add(sql);
}
}
return sqlList;
} catch (Exception ex) {
throw new Exception(ex.getMessage());
}
}
/**
*
* @Title: execute
* @Description: TODO(这里用一句话描述这个方法的作用)
* @param @param conn
* @param @param sqlFile
* @param @throws Exception 设定文件
* @return void 返回类型
* @throws
*/
public void execute(Connection conn, String sqlFile){
try {
Statement stmt = null;
List<String> sqlList = loadSql(sqlFile);
stmt = conn.createStatement();
for (String sql : sqlList) {
stmt.addBatch(sql);
}
int[] rows = stmt.executeBatch();
} catch (Exception e) {
e.printStackTrace();
}finally{
// clise();
}
}