简体   繁体   中英

Running multiple SQL statements from Groovy

I'm having problems running multiple SQL statements in one activaction from Groovy.

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

The error I'm getting is "You have an error in your SQL syntax". What gives?

You can simply augment the following jdbc url parameter to your connection string

http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-configuration-properties.html#allowMultiQueries

From the docs:

Allow the use of ';' to delimit multiple queries during one statement (true/false), defaults to 'false'

For example:

Sql.newInstance("jdbc:mysql://localhost?allowMultiQueries=true", "usre", "pass", "com.mysql.jdbc.Driver")

The problem is because groovy uses JDBC's Statement.execute(), which expects on statement. Here is a replacement class for Groovy's Sql that works around this problem (but lacks in functionality)

/**
 * 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();
    }
  }
}

Groovy开发人员之一的Paul King评论了我打开的问题,你可以告诉mysql允许多个语句(其他RDBMS不一定支持)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM