Praveen Hiremath
Praveen Hiremath

Reputation: 4219

Execute Filename.sql file in Java using MyBatis

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.

Upvotes: 2

Views: 5093

Answers (2)

Praveen Hiremath
Praveen Hiremath

Reputation: 4219

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();
    }
}

Upvotes: 0

Persia
Persia

Reputation: 895

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();

Upvotes: 4

Related Questions