[英]Executing multiple native queries in one go
I'm wondering if it is possible to execute several semicolon-separated SQL update queries with one SQLQuery#executeUpdate()
call in Hibernate (3.2).我想知道是否可以通过 Hibernate (3.2) 中的一个SQLQuery#executeUpdate()
调用来执行几个以分号分隔的 SQL 更新查询。
I have string containing multiple updates like this:我有包含多个更新的字符串,如下所示:
String statements = "UPDATE Foo SET bar=1*30.00 WHERE baz=1;
UPDATE Foo SET bar=2*45.50 WHERE baz=2;...";
I'm trying to do我正在尝试做
Query query = session.createSQLQuery(statements);
query.executeUpdate();
But keep getting the following error但不断收到以下错误
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
You have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version for the right syntax to use near
'UPDATE Foo SET bar=Y WHERE ' at line 3
If I execute the contents of the statements
by hand I get no errors so I'm assuming the multiple semicolon-separated queries are causing trouble somewhere in Hibernate or JDBC.如果我手动执行statements
的内容,我不会收到任何错误,所以我假设多个分号分隔的查询在 Hibernate 或 JDBC 的某个地方造成了麻烦。
Is it better to just split the statements
string and do createSQLQuery(statement).executeUpdate()
individually for each line?只拆分statements
字符串并为每一行单独执行createSQLQuery(statement).executeUpdate()
会更好吗?
An alternative is to use a CASE statement.另一种方法是使用 CASE 语句。 For example:例如:
UPDATE Foo
SET bar =
CASE baz
WHEN 1 THEN 'X'
WHEN 2 THEN 'Y'
END CASE
WHERE baz in (1,2)
well you have to at least embrace X and Y with single quotes, I'd say.好吧,我会说,您至少必须用单引号括住 X 和 Y。
What you can do is use batch statements, basically before you execute your query call the addBatch(string query);
您可以做的是使用批处理语句,基本上在执行查询之前调用addBatch(string query);
method, then when all your queries are in the batch just call the executeBatch()
method.方法,然后当所有查询都在批处理中时,只需调用executeBatch()
方法。 That will perform them all for you in the order you added the mto the batch.这将按照您将 m 添加到批次的顺序为您执行所有操作。
also: the error in your syntax is you need put in quotes 'Y'
or 'X'
另外:你的语法错误是你需要用引号'Y'
或'X'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.