[英]Running multiple SQL statements 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
我得到的错误是“你的SQL语法有错误”。 是什么赋予了?
您可以简单地将以下jdbc url参数扩充到您的连接字符串
来自文档:
允许使用';' 在一个语句中分隔多个查询(true / false),默认为'false'
例如:
Sql.newInstance("jdbc:mysql://localhost?allowMultiQueries=true", "usre", "pass", "com.mysql.jdbc.Driver")
问题是因为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();
}
}
}
Groovy开发人员之一的Paul King评论了我打开的问题,你可以告诉mysql允许多个语句(其他RDBMS不一定支持)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.