Execute SQL Scripts in Grails Bootstrap or Integration Tests

I recently had to execute some SQL scripts when a Grails applications starts up to insert test data into the database.
Executing sql scripts is easy. Just open the SQL File and read the contents of the Script to a String variable.

String sqlFilePath = 'path/to/your/script.sql'
String sqlString = new File(sqlFilePath).text

Create a SQL connection and use it’s execute(String sql) method to execute your script. To configure the SQL connection, you can use the settings from your DataSource.groovy .

def sql = Sql.newInstance(ConfigurationHolder.config.dataSource.url, ConfigurationHolder.config.dataSource.username, ConfigurationHolder.config.dataSource.password, ConfigurationHolder.config.dataSource.driverClassName)
sql.execute(sqlString)

Here is the full sourcecode:

import groovy.sql.Sql
import org.codehaus.groovy.grails.commons.ConfigurationHolder

String sqlFilePath = 'path/to/your/script.sql'
String sqlString = new File(sqlFilePath).text
def sql = Sql.newInstance(ConfigurationHolder.config.dataSource.url, ConfigurationHolder.config.dataSource.username, ConfigurationHolder.config.dataSource.password, ConfigurationHolder.config.dataSource.driverClassName)
sql.execute(sqlString)

This can be very useful when you have to insert a lot of test data into the database.

Short URL for this post: http://wp.me/p4nxik-9s
This entry was posted in Groovy and Grails and tagged , , , . Bookmark the permalink.

2 Responses to Execute SQL Scripts in Grails Bootstrap or Integration Tests

  1. Pingback: Blog bookmarks 06/01/2010 « My Diigo bookmarks

  2. Pingback: Execute SQL Scripts in Grails Bootstrap or Integration Tests - Grails Execute SQL

Comments are closed.