特定の日付のデータベース内の行数をカウントするだけの、次の小さな 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 は初めてなので、提案は大歓迎です。前もって感謝します!