在 sql 查询中使用 java.sql.Timestamp 对象

2022-01-13 00:00:00 timestamp sql oracle jdbc java

我正在尝试在 java 中运行一个查询,该查询使用 java.sql.Timestamp 对象作为要在 where 子句中进行比较的日期.

I am trying to run a query in java that uses a java.sql.Timestamp object as the date to compare with in the where clause.

这是用 Java 构建的查询字符串的方式

Here is how the query string that is built in Java

 String getTransactionsSQL =  "Select transaction_seq " +
    "From transactions ct " +
    "Where id = 'ABCD'" + 
    "And ct.out_msg_timestamp" +
    "<= to_date('" + parseDate.getTimeStamp() +"','YYYY-MM-DD HH:MI:SS..')" +
    "order by transaction_seq"; 

语句 parseDate.getTimeStamp() 返回一个包含日期的 java.sql.TimeStamp 对象.这是 System.out.println(parseDate.getTimeStamp());

The statement parseDate.getTimeStamp() returns a java.sql.TimeStamp object that contains a date. Here is an example output of System.out.println(parseDate.getTimeStamp());

2011-03-07 05:47:57.0

当我运行上面的查询时,我得到了这个错误

When i run the above query i get this error

 java.sql.SQLException: ORA-01843: not a valid month

有什么线索吗?

推荐答案

使用 PreparedStatement:http://download.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html

Use PreparedStatement: http://download.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html

切勿使用字符串连接将参数传递给 SQL 命令(安全风险:SQL 注入)!

Never use string concatenation to pass arguements to SQL commands (security risk: SQL injection)!

相关文章