我有以下小型 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 的新手,因此欢迎提出任何建议。提前致谢!