2010-11-26 33 views
4

我在Groovy的一個活動中運行多個SQL語句時遇到問題。從Groovy運行多個SQL語句

sql = Sql.newInstance("jdbc:mysql://localhost/", "usre", "pass", "com.mysql.jdbc.Driver") 
sql.execute("USE foo; "); // this works 
sql.execute("USE foo; USE foo;"); // this fails miserably 

我收到的錯誤是「您的SQL語法錯誤」。是什麼賦予了?

+0

http://stackoverflow.com/questions/3024490/soapui-groovy -scripts-executed-multiple-sql-statements-in-one-goes – ajreal 2010-11-26 15:30:34

+0

@ajreal - 我會解決這個問題......但爲什麼***會發生這種情況呢?創建問題 - http://jira.codehaus.org/browse/GROOVY-4540 – ripper234 2010-11-26 19:00:27

回答

1

問題是因爲groovy使用JDBC的Statement.execute(),它需要在語句上。下面是對Groovy的SQL替代類,解決此問題的工作(但在功能上缺乏)

/** 
* Not related to mysql, just to distinguish it from Groovy's Sql class 
* Created to solve this problem: http://stackoverflow.com/questions/4286483/running-multiple-sql-statements-from-groovy 
*/ 
public class MySql { 
    private final String password; 
    private final String connectionString; 
    private final String user; 

    public static newInstance(String connectionString, String user, String password, String driverName) { 
    Class.forName(driverName).newInstance(); 
    return new MySql(connectionString, user, password); 
    } 

    public MySql(String connectionString, String user, String password) { 
    this.connectionString = connectionString; 
    this.user = user; 
    this.password = password; 
    } 

    void execute(String query) { 
    Connection conn = DriverManager.getConnection(connectionString, user, password); 
    try { 
     Statement statement = conn.createStatement(); 
     for (String subQuery : query.split(";")) 
     { 
     if (subQuery.trim() == '') 
      continue; 

     statement.addBatch subQuery 
     } 
     statement.executeBatch(); 
    } 
    finally { 
     conn.close(); 
    } 
    } 
} 
0

保羅·金的Groovy的開發商之一,在我開了,你可以告訴MySQL允許多個語句的問題評論(這並不一定是由其他RDBMS支持)