Running MySQL script from java program

Running My SQL script from Java can be done using the below program.

Required jar files:

  • http://www.java2s.com/Code/Jar/i/Downloadibatis3core300242jar.htm
  • https://dev.mysql.com/downloads/connector/j/

Program:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.ibatis.jdbc.ScriptRunner;

public class SqlScriptInJava {

    public static void main(String[] args) throws ClassNotFoundException,SQLException {

        String sqlscript = "C:/test.sql";
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb", "username", "password");
        Statement stmt = null;

        try {
            ScriptRunner sr = new ScriptRunner(con);
            Reader reader = new BufferedReader(new FileReader(sqlscript));
            sr.runScript(reader);
        } catch (Exception e) {
            System.err.println("Failed to Execute" + sqlscript + " The error is " + e.getMessage());
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *