2

我正在使用 Groovy 的 groovy.sql.Sql 来查询 Oracle 10g 数据库。它工作得很好,除了我在firstRow遇到的一个奇怪问题。从本质上讲,我java.sql.SQLException: Invalid column type每次使用它都会得到一个——尽管eachRow有效。

有没有其他人遇到过这个?如果是这样,是否有解决方法?这发生在 Groovy 1.8.8 和 2.1.1 中。到目前为止,我只在 Windows XP 上尝试过。

示例代码:

import groovy.sql.Sql

// ojdbc14_ver_10_2_0_4.jar and orai18n_ver_10_2_0_4.jar is in the classpath
// Oracle Database 10g Enterprise Edition Release 10.2.0.5.0 - 64bit

sql = Sql.newInstance("jdbc:oracle:thin:@dbhost:1500:DBNAME", "user", "pass", "oracle.jdbc.driver.OracleDriver")


// This should return only one row (verified by querying the database).
// You can use any query that returns only one row.
String query = "select ITEM_A, ITEM_B, ITEM_C from MY_TBL where ITEM_D = 1233"

Long itemA = 0L
Long itemB = 0L, itemC = 0L

Integer rowCount = 0
sql.eachRow(query) { row ->
    itemA = row.ITEM_A
    itemB = row.ITEM_B
    itemC = row.ITEM_C
    rowCount++
}
assert rowCount <= 1 // 0 or 1 rows returned

println "Item A = $itemA"
println "Item B = $itemB"
println "Item C = $itemC"
// works fine

// now we have a problem:
sql.firstRow(query) { row ->
    itemA = row.ITEM_A
    itemB = row.ITEM_B
    itemC = row.ITEM_C
}
println "Item A = $itemA"
println "Item B = $itemB"
println "Item C = $itemC"

这将产生以下输出:

>>groovy firstRowTest.groovy
Item A = 640
Item B = 90
Item C = 90
25-Mar-2013 13:49:24 groovy.sql.Sql$AbstractQueryCommand execute
WARNING: Failed to execute:
                select ITEM_A, ITEM_B, ITEM_C from MY_TBL where ITEM_D = 1233
              because: Invalid column type
Caught: java.sql.SQLException: Invalid column type
java.sql.SQLException: Invalid column type
        at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
        at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
        at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:208)
        at oracle.jdbc.driver.OraclePreparedStatement.setObjectCritical(OraclePreparedStatement.java:9262)
        at oracle.jdbc.driver.OraclePreparedStatement.setObjectInternal(OraclePreparedStatement.java:8843)
        at oracle.jdbc.driver.OraclePreparedStatement.setObjectInternal(OraclePreparedStatement.java:9565)
        at oracle.jdbc.driver.OraclePreparedStatement.setObject(OraclePreparedStatement.java:9548)
        at firstRowTest.run(firstRowTest.groovy:30)
4

2 回答 2

2

firstRow不采用闭包作为参数,你能看看这是否给出了同样的错误?

def frow = sql.firstRow(query)
itemA = frow.ITEM_A
itemB = frow.ITEM_B
itemC = frow.ITEM_C

我怀疑,它正在尝试调用此方法,并将 Closure 作为参数传递

于 2013-03-25T14:15:41.187 回答
1

我相信你可以说:

sql.firstRow(query).with{row ->
    itemA = row.ITEM_A
    itemB = row.ITEM_B
    itemC = row.ITEM_C     
}

这确实允许您传入从 firstRow 方法返回的 GroovyRowResult 的闭包。

于 2013-03-26T15:19:38.763 回答