我在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 :(得分:8)
您可以简单地将以下jdbc url参数扩充到您的连接字符串
来自文档:
允许使用';'划界 一个语句中的多个查询 (true / false),默认为'false'
例如:
Sql.newInstance("jdbc:mysql://localhost?allowMultiQueries=true", "usre", "pass", "com.mysql.jdbc.Driver")
答案 1 :(得分:1)
问题是因为groovy使用JDBC的Statement.execute(),它需要on语句。这是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();
}
}
}
答案 2 :(得分:0)
Groovy开发人员之一的Paul King评论了我打开的问题,你可以告诉mysql允许多个语句(其他RDBMS不一定支持)