Execute SQL Scripts in Grails Bootstrap or Integration Tests
程序员文章站
2022-05-19 22:13:41
...
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.
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 .
Here is the full sourcecode:
This can be very useful when you have to insert a lot of test data into the database.
groovy.sql.Sql中的execute()只能执行一行script代码,且不能执行空行,修正后的代码如下:
参考文章:
http://blog.oio.de/2010/05/31/execute-sql-scripts-in-grails-bootstrap-or-integration-tests/
http://www.intelligrape.com/blog/2010/09/14/grails-execute-sql-script-in-bootstrap/
http://grails.1312388.n4.nabble.com/Running-a-mysql-dump-from-grails-BootStrap-fails-unexpectedly-td3690734.html
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.
groovy.sql.Sql中的execute()只能执行一行script代码,且不能执行空行,修正后的代码如下:
String sqlFilePath = 'path/to/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) sqlString.eachLine {line -> if(line.trim())sql.execute(line) }
参考文章:
http://blog.oio.de/2010/05/31/execute-sql-scripts-in-grails-bootstrap-or-integration-tests/
http://www.intelligrape.com/blog/2010/09/14/grails-execute-sql-script-in-bootstrap/
http://grails.1312388.n4.nabble.com/Running-a-mysql-dump-from-grails-BootStrap-fails-unexpectedly-td3690734.html