I’m working with Grails 3.0.9 and need to run a MySQL script file from inside a controller method. My approach isn’t working and I’m getting syntax errors.
Here’s my current implementation:
import groovy.sql.Sql
import grails.util.Holders
def void resetTables() {
String scriptPath = 'scripts/reset_tables.sql'
String queryContent = new File(scriptPath).text
def connection = Sql.newInstance(Holders.config.dataSource.url,
Holders.config.dataSource.username,
Holders.config.dataSource.password,
Holders.config.dataSource.driverClassName)
connection.execute(queryContent)
}
My SQL file reset_tables.sql
contains:
SET FOREIGN_KEY_CHECKS = 0;
TRUNCATE user_data;
TRUNCATE order_info;
TRUNCATE product_details;
SET FOREIGN_KEY_CHECKS = 1;
The error I’m seeing is:
WARN org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Warning Code: 1064, SQLState: 42000
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'TRUNCATE user_data;
The weird thing is that when I run this same SQL script directly in MySQL it works fine. So the issue seems to be with how I’m executing it through Grails, not the SQL itself. What am I doing wrong here?