我有以下小Groovy腳本,只是在特定的日期數據庫中的行數。如何使用Groovy中的變量使用PL/SQL to_date?
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/[email protected]: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')
警告
有沒有更好的方式做到這一點,而不是以不同的方式對變量進行格式化?我是Groovy的新手,因此歡迎任何建議。提前致謝!
我想你需要一個java.sql.Date實例,以便將它與沒有時間戳的Date列進行比較。 – 2009-11-09 20:39:06
謝謝Christoph,我想我已經解決了它。 – 2009-11-09 22:09:49