How to run a MySQL Script using Java

java mysql

In this tutorial, I will show you how to run a MySQL script file using ibatis ScriptRunner class. First, download the ibatis and Mysql JDBC Driver, and add the jar files into your classpath.

Now, run below code. It will execute a script.sql file.
package com.mkyong;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import com.ibatis.common.jdbc.ScriptRunner;
 @author Dhinakaran Pragasam
public class RunSqlScript {
	 * @param args
	 *            the command line arguments
	public static void main(String[] args) throws ClassNotFoundException,
		SQLException {
		String aSQLScriptFilePath = "path/to/sql/script.sql";
		// Create MySql Connection
		Connection con = DriverManager.getConnection(
			"jdbc:mysql://localhost:3306/database", "username", "password");
		Statement stmt = null;
		try {
			// Initialize object for ScripRunner
			ScriptRunner sr = new ScriptRunner(con, false, false);
			// Give the input file to Reader
			Reader reader = new BufferedReader(
                               new FileReader(aSQLScriptFilePath));
			// Exctute script
		} catch (Exception e) {
			System.err.println("Failed to Execute" + aSQLScriptFilePath
					+ " The error is " + e.getMessage());

  1. sql script should have an semi colen (;) for each end of the statement.
  2. You sql script does not have any select statement.


  1. ibatis ScriptRunner JavaDoc
Tags :

About the Author

Dhina Prakash
Open Source Developer, TenthPlanet Technologies.


  • naresh parimi

    my project is Maven based. here i am not able to fine maven dependency for ‘ibatis ScriptRunner’

  • Mehdi

    realy helpfull, quick and easy to implement
    thank you :-)

  • mkyong

    Here is an alternative way to run a MySQL script without using any third party library.

    • Armen


      Thenks, but where we can put the file? I am always have file not found exception, I trying run it from JSF managed bean.

      Best Regards