[英]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.