Pages Navigation Menu

Coding is much easier than you think

How To Run A MySQL Script Using Java

 
In this tutorial, we shall learn about running a MySQL script file using ibatis ScriptRunnerclass.

Download the following libraries and add them into your classpath.

 

dwd2
Download It – ibatis      &     Mysql JDBC Driver

 
package com.simplecode.jdbc;

import java.io.Reader;
import java.io.FileReader;
import java.io.BufferedReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.ibatis.common.jdbc.ScriptRunner;

public class ExecuteSqlScript {

private static final String DB_DRIVER = "com.mysql.jdbc.Driver";
private static final String DB_CONNECTION = "jdbc:mysql://localhost:3306/simplecodedb";
private static final String DB_USER = "username";
private static final String DB_PASSWORD = "password";

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

String sqlScriptFilePath = "C:/sql/script.sql";

// Create MySQL Connection
Class.forName(DB_DRIVER);
	
Connection connection = DriverManager.getConnection(DB_CONNECTION, DB_USER,DB_PASSWORD);

	try
        {
		// Initialize object for ScriptRunner
		ScriptRunner runner = new ScriptRunner(connection, false, false);
		// Give the input file to Reader
		Reader br = new BufferedReader(new FileReader(sqlScriptFilePath));
		// Execute script
		runner.runScript(br);

	    }
         catch (Exception e)
            {
		System.out.println("Exception Occoured" + e.getMessage());
	    }
	}
}

 
You may be also interested in
How to get Primary Key Of Inserted Record in JDBC?

 

Note
  1. You sql script should not have any select statement.
  2. sql script should have a semi colon (;) for each end of the statement.

 
dwd2
Download It – ExecuteSqlScript.java

 

References