0

特定の日付のデータベース内の行数をカウントするだけの、次の小さな Groovy スクリプトがあります。

import groovy.sql.Sql

def today= new GregorianCalendar()
def dateString = "${today.get(Calendar.MONTH)+1}/${today.get(Calendar.DAY_OF_MONTH)-1}/${today.get(Calendar.YEAR)}"

def sql = Sql.newInstance("jdbc:oracle:thin:bc/bc@nemesis:1521:billctr", "bc","bc", "oracle.jdbc.OracleDriver")

def sqlLine = "select count(id) as count from bc_payment where trunc(paymentdate) = to_date(${dateString}, \'MM/DD/YYYY\')"
println(sqlLine)
def payCount = sql.execute(sqlLine)
println payCount

to_date には、渡す日付を一重引用符で囲む必要があります。それらを省略した場合は取得できますSQLException: Invalid column typeが、変数を \' で囲むと、Groovy から警告が表示されます

WARNING: In Groovy SQL please do not use quotes around dynamic expressions (which start with $) as this means we cannot use a JDBC PreparedStatement and so is a security hole. Groovy has worked around your mistake but the security hole is still there. The expression so far is: select count(id) as count from bc_payment where trunc(paymentdate) = to_date('?', 'MM/DD/YYYY')

to_dateや変数のフォーマットを変えずにこれを行うより良い方法はありますか? Groovy は初めてなので、提案は大歓迎です。前もって感謝します!

4

3 に答える 3

2

同様の問題を抱えている開発者による遅い回答。

宣言を変更することで問題を解決できることがわかりました。

def sqlLine = "... ${yourString} ..."

... sqlLine を GStringImpl オブジェクトとして作成します。代わりに、次のように sqlLine を宣言すると:

String sqlLine = "... ${yourString} ..."

...変数をインラインで解決し、文字列オブジェクトを受け取ります。このようにして、groovy.sql.Sql は、SQL を動的に作成したことを決して知りません。

于 2012-02-01T09:59:15.740 に答える