我有一堆sql脚本,应该在java Web应用程序启动时升级数据库.
我尝试使用ibatis scriptrunner,但它在定义触发器时失败了,其中";" 字符不标记声明的结尾.
现在我已经编写了我自己的脚本运行版本,它基本上可以完成这项工作,但会破坏可能的格式和注释,尤其是在"创建或替换视图"中.
public class ScriptRunner { private final DataSource ds; public ScriptRunner(DataSource ds) { this.ds = ds; } public void run(InputStream sqlStream) throws SQLException, IOException { sqlStream.reset(); final Statement statement = ds.getConnection().createStatement(); ListsqlFragments = createSqlfragments(sqlStream); for (String toRun : sqlFragments) { if (toRun.length() > 0) { statement.execute(toRun); } } } private static List createSqlfragments(InputStream sqlStream) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(sqlStream)); List ret = new ArrayList (); String line; StringBuilder script = new StringBuilder(); while ((line = br.readLine()) != null) { if (line.equals("/")) { ret.add(removeMultilineComments(script)); script = new StringBuilder(); } else { //strip comments final int indexComment = line.indexOf("--"); String lineWithoutComments = (indexComment != -1) ? line.substring(0, indexComment) : line; script.append(lineWithoutComments).append(" "); } } if (script.length() > 0) { ret.add(removeMultilineComments(script)); } return ret; } private static String removeMultilineComments(StringBuilder script) { return script.toString().replaceAll("/\\*(.*?)\\*/", "").trim(); }
是否有一个干净的方法来解决这个问题?我还没有看到有什么东西在休眠吗?或者我可以以某种方式将输入流传递给sqlplus?除了我对格式化的担忧之外,我怀疑这段代码没有错误,因为我对pl/sql语法知之甚少.
使用以下解决方案供您参考,我已经尝试并测试并成功运行.
private static String script_location = ""; private static String file_extension = ".sql"; private static ProcessBuilder processBuilder =null; public static void main(String[] args) { try { File file = new File("C:/Script_folder"); File [] list_files= file.listFiles(new FileFilter() { public boolean accept(File f) { if (f.getName().toLowerCase().endsWith(file_extension)) return true; return false; } }); for (int i = 0; i使用此代码段并尝试运行.
Thanx用户在下面的链接中提到了解决方案:
http://forums.sun.com/thread.jspa?threadID=5413026
问候| 尼廷
2> 小智..:iBATIS ScriptRunner有一个
setDelimiter(String, boolean)
方法.这允许你有一个字符串而不是";" 成为SQL语句之间的分隔符.在Oracle SQL脚本中,使用"/"(斜杠)分隔语句.
在您的Java代码中,在调用
runScript
do 之前setDelimter("/", false)
,它将指示ScriptRunner将"/"识别为语句分隔符.