gpt4 book ai didi

sql - 如何在 groovy 中使用相同的代码同时执行查询和 DML 语句?

转载 作者:行者123 更新时间:2023-12-04 01:12:42 24 4
gpt4 key购买 nike

我是 SQL Fiddle 的作者.这些知识可能有助于构建这个问题:

我正在尝试编写一些 Groovy 代码,这些代码将在我的数据库中执行任意查询/DML 代码。基于我对 Groovy Sql API 的阅读,所有这些功能都需要一些非常特别的东西。例如,“eachRow”期望返回一个结果集;如果它没有返回(例如在 UPDATE 语句的情况下),则使用它会引发错误。我可以用任何类型的语句调用“执行”,但是在使用它时我无法取回我的 SELECT 语句的结果集(这绝对是一个要求)。

在这一点上,我想我可能不得不放弃 Groovy 的 Sql 库,转而使用一些较低级别的 JDBC 实现。我想这会是一种耻辱,但如果有必要,我愿意去那里。不过,我非常希望尽可能将其保留为 Groovy-esqe。我该怎么做呢?

最佳答案

看看 execute() 的品种返回 boolean 的方法.根据文档的返回类型:

true if the first result is a ResultSet object; false if it is an update count or there are no results



CREATE、DROP 和 INSERT 已在示例中提及。我希望它的工作方式与 UPDATE 相同。

对于 SELECT,必须检查标志是否存在 ResultSet展示。如果是,则可以触发第二个查询以获取行。例如:
//If statement qualifies for select statements
//because .execute() will return true if there is a ResultSet
//present. It will be false for CREATE, UPDATE and DROP.
if( sql.execute("select name from Foo") ) {

//Fire the second query to get the rows in case of SELECT query
result = sql.rows "select name from Foo"
}

return result

更新
如果出于性能原因担心执行查询两次,则可以尝试以下方法:
def queryString = "update Foo set name = 'hello' where name = 'baz'"

try {
sql.query queryString, { ResultSet rs ->
//Result set returned for select query only
//For all other cases exception is thrown
}
} catch( java.sql.SQLException ) {
//Throws exception for any other type of query
//By now you should be smart enough exception is not
//thrown for any other cause.

sql.execute queryString
}

关于sql - 如何在 groovy 中使用相同的代码同时执行查询和 DML 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22592508/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com