简体   繁体   English

为什么语句有效但没有在java,jdbc,oracle中编写声明?

[英]Why statement works but not prepared satement in java, jdbc, oracle?

I am trying to write a query and get results from oracle db using java and jdbc. 我正在尝试编写查询并使用java和jdbc从oracle db获取结果。 My problem is the same query works if I try with statement, but the same query does not work if I use preparedStatement. 我的问题是同样的查询工作,如果我尝试使用语句,但如果我使用prepareStatement相同的查询不起作用。 Statement Code: (Here I get real count value) 声明代码:(这里我得到真正的计数值)

Statement stmt = con.createStatement();
String sql = "SELECT COUNT(*) CNT FROM DB.TABLE WHERE DAY = TO_DATE('" + sqlDate + "','YYYY-MM-DD')";
rs = stmt.executeQuery(sql);

PreparedStatement Code: (Here I get count value zero) PreparedStatement代码:(这里我的计数值为零)

Date sqlDate = new java.sql.Date(someJava.Util.Date.getTime());// = 2015-09-24
sqlString = "SELECT COUNT(*) CNT FROM DB.TABLE WHERE DAY = TO_DATE(?,'YYYY-MM-DD')";
pstmt = con.prepareStatement(sqlString);                                        
pstmt.setDate(1, sqlDate);          
rs = pstmt.executeQuery();

When I sysout my sqlDate prints like: 2015-09-24. 当我sysout我的sqlDate打印像:2015-09-24。

I have same problem with some other queries. 我对其他一些查询也有同样的问题。 Can anyone know whats wrong here? 任何人都知道这里有什么不对吗?

The TO_DATE function converts a string to a date given a certain format. TO_DATE函数将字符串转换为给定特定格式的日期。 So the parameter passed to the prepared statement should be the String to be converted by the Oracle function: 因此传递给预准备语句的参数应该是Oracle函数要转换的String

pstmt.setString(1, sqlDate.toString());

Or you can change the query so that the parameter is the date itself and pass the java.sql.Date object to the prepared statement: 或者,您可以更改查询,以便参数是日期本身,并将java.sql.Date对象传递给预准备语句:

sqlString = "SELECT COUNT(*) CNT FROM DB.TABLE WHERE DAY = ?";
pstmt.setDate(1, sqlDate());

Note that, for the normal statement query: 注意,对于正常的语句查询:

String sql = "SELECT COUNT(*) CNT FROM DB.TABLE WHERE DAY = TO_DATE('" + sqlDate + "','YYYY-MM-DD')";

the String concatenation will append the string representation of the object, ie it is equivalent to: 字符串连接将附加对象的字符串表示形式,即它等效于:

String sql = "SELECT COUNT(*) CNT FROM DB.TABLE WHERE DAY = TO_DATE('" + sqlDate.toString() + "','YYYY-MM-DD')";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM