简体   繁体   English

从Groovy运行多个SQL语句

[英]Running multiple SQL statements from Groovy

I'm having problems running multiple SQL statements in one activaction from Groovy. 我在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

The error I'm getting is "You have an error in your SQL syntax". 我得到的错误是“你的SQL语法有错误”。 What gives? 是什么赋予了?

You can simply augment the following jdbc url parameter to your connection string 您可以简单地将以下jdbc url参数扩充到您的连接字符串

http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-configuration-properties.html#allowMultiQueries 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' 在一个语句中分隔多个查询(true / false),默认为'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. 问题是因为groovy使用JDBC的Statement.execute(),它需要on语句。 Here is a replacement class for Groovy's Sql that works around this problem (but lacks in functionality) 这是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();
    }
  }
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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