2

I have a Filename.sql(Mysql Script) file which has multiple SQL Statements. I'm using MyBatis as persistence framework and MySQL as the database. I want to execute the Filename.sql file in a Java program.

NOTE: I don't want to execute the queries as separate SQL Statements.

This operation is equivalent to source Filename.sql in MySQL command prompt.

2

2 Answers 2

4

you can use org.apache.ibatis.jdbc.ScriptRunner to do this:

ScriptRunner runner = new ScriptRunner(dataSource.getConnection());
runner.setAutoCommit(true);
runner.setStopOnError(true);
runner.runScript(getResourceAsReader("Filename.sql"));
runner.closeConnection();
Sign up to request clarification or add additional context in comments.

2 Comments

What about myBatis?
it is in the mybatis repo under the ibatis pkg path -- github.com/mybatis/mybatis-3/blob/…
0
private void runMysqlScript(String sqlScriptFilePath) {

    try {
        // Create MySQL Connection
        Class.forName(driverClassName);
        Connection connection = 
                DriverManager.getConnection(jdbcURL, jdbcUsername, jdbcPassword);
        // Initialize object for ScriptRunner
        ScriptRunner runner = new ScriptRunner(connection);
        // Give the input file to Reader
        Reader br = new BufferedReader(new FileReader(sqlScriptFilePath));
        // Execute script
        runner.runScript(br);

    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

1 Comment

What about myBatis?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.