How to Execute SQL Script File in Java?

Vladimir picture Vladimir · Jan 15, 2010 · Viewed 128.1k times · Source

I want to execute an SQL script file in Java without reading the entire file content into a big query and executing it.

Is there any other standard way?

Answer

Ruslans Uralovs picture Ruslans Uralovs · Jun 16, 2010

There is great way of executing SQL scripts from Java without reading them yourself as long as you don't mind having a dependency on Ant. In my opinion such a dependency is very well justified in your case. Here is sample code, where SQLExec class lives in ant.jar:

private void executeSql(String sqlFilePath) {
    final class SqlExecuter extends SQLExec {
        public SqlExecuter() {
            Project project = new Project();
            project.init();
            setProject(project);
            setTaskType("sql");
            setTaskName("sql");
        }
    }

    SqlExecuter executer = new SqlExecuter();
    executer.setSrc(new File(sqlFilePath));
    executer.setDriver(args.getDriver());
    executer.setPassword(args.getPwd());
    executer.setUserid(args.getUser());
    executer.setUrl(args.getUrl());
    executer.execute();
}