在Groovy / Gradle中执行Sql脚本文件

时间:2014-02-12 20:07:42

标签: mysql groovy gradle

def db = [
    moduleGroup: 'mysql',
    moduleName: 'mysql-connector-java',
    moduleVersion: '5.1.18',
    driver: "com.mysql.jdbc.Driver",
    url: 'jdbc:mysql://localhost:3306/bham',
    user: mySqlUser,
    password: mySqlPassword
]

configurations {
    sql
}    


task connect << {

        // This is needed to get mySql driver onto the Groovy/Gradle classpath 
        configurations.sql.each { file ->
          println "Adding URL: $file"
          gradle.class.classLoader.addURL(file.toURI().toURL())
        }

        def sql = groovy.sql.Sql.newInstance(db.url, db.user, db.password, db.driver)

        sql.execute("actStatusCodeLkp.sql") 
        String sqlFilePath = "src/main/resources/sqlscripts/actStatusCodeLkp.sql"
        String sqlString = new File(sqlFilePath).text
        sql.execute(sqlString)

        sql.close()

     }

actStatusCodeLkp.sql

insert into act_status_code (id, code, display_name, code_system_name, code_system) values (1, 'active', 'active', 'ActStatus', '2.16.840.1.113883.5.14');
insert into act_status_code (id, code, display_name, code_system_name, code_system) values (2, 'cancelled', 'cancelled', 'ActStatus', '2.16.840.1.113883.5.14');
insert into act_status_code (id, code, display_name, code_system_name, code_system) values (3, 'aborted', 'aborted', 'ActStatus', '2.16.840.1.113883.5.14');
insert into act_status_code (id, code, display_name, code_system_name, code_system) values (4, 'completed', 'completed', 'ActStatus', '2.16.840.1.113883.5.14');

似乎sql.execute命令没有将文件标记为4个不同的插入语句并抛出。

Caused by: 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 'insert into act_status_code (id, code, display_name, code_system_name, code_syst' at line 2
        at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)

如果我只在文件中保留一个插入语句,它就可以工作。这里干净的工作是什么,在网上找不到任何关于这个的信息。 此外,使用maven时,我可以使用sql-maven-plugin运行相同的sql文件。

2 个答案:

答案 0 :(得分:5)

这样的事情对我有所帮助。注意在属性

中获取allowMultiQueries:'true'
def props = [user: grailsApplication.config.dataSource.username, password: grailsApplication.config.dataSource.password, allowMultiQueries: 'true'] as Properties
    def url = grailsApplication.config.dataSource.url
    def driver = grailsApplication.config.dataSource.driverClassName


    def sql = Sql.newInstance(url, props, driver)

答案 1 :(得分:1)

您还可以通过以下方式更改sql以使语句成为一个查询:

insert into act_status_code (id, code, display_name, code_system_name, code_system) values 
(1, 'active', 'active', 'ActStatus', '2.16.840.1.113883.5.14'),
(2, 'cancelled', 'cancelled', 'ActStatus', '2.16.840.1.113883.5.14'),
(3, 'aborted', 'aborted', 'ActStatus', '2.16.840.1.113883.5.14'),
(4, 'completed', 'completed', 'ActStatus', '2.16.840.1.113883.5.14');
相关问题