Grails: execute sql script in Bootstrap

14 / Sep / 2010 by Anshul Sharma 4 comments

This blog might help you to speed up your bootstrap process, especially when you need to populate records in tables.
Earlier we used populate our database table by reading line by line from a CSV file and creating Domain Class object ad Save. But this was taking a huge time. And in our case, this data (more like a static information) was always same. So we came up with an idea – we took mysqldump for this particular table and saved it to our application’s web-app/data directory. Now the thing was, we just need to execute this “sql” file during bootstrap!

Below is the example how to execute database dump files in bootstrap!

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

String sqlFilePath = ApplicationHolder.application.parentContext.servletContext.getRealPath("/data/table_dump.sql")
String sqlString = new File(sqlFilePath).text
Sql sql = Sql.newInstance(CH.config.dataSource.url, CH.config.dataSource.username,
CH.config.dataSource.password, CH.config.dataSource.driverClassName)
sql.execute(sqlString)

Hope this helped!

Cheers!
Anshul Sharma

FOUND THIS USEFUL? SHARE IT

comments (4)

  1. Paolo

    GrewGreat !!!!
    And how executing a mysqldump in the same way ? I mean … How to execute a backup dump in a specific directory ?
    Thanks

    Reply
  2. Bhavesh Shah

    I am working on grails project with Database MySQL, i want to take a backup of Database through project. How to do this thing. Please give me a solution as soon as Possible.
    Thanks. Bhavesh Shah

    Reply
  3. Parag

    Hi Anshul….
    Thanks foe nice post.I have one query regarding running sql script in bootstrap..
    Suppose we have to run total Database backup (mydatabase.sql) which contains all create,insert queries of tables.
    How can we do this.?
    Or we have to create separate separate sql files for only insert..Please guide me..
    Thanking You..

    Reply
  4. jlebrijo

    hi Anshul,

    thanks for the post.

    The Oracle databases do not run with semicolon at the end of sentence.

    Then I have to do a variation:
    String sqlString = new File(sqlFilePath).eachLine {
    sql.execute(it)
    }

    Separating sentences in lines and executing each one.

    Hope this help to Oracle victims 😉

    Reply

Leave a Reply

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