-1

我正在使用 MS-SQL 服务器。我在Convert. 这是我的查询:

String query1="select * from pat.dbo.Demand_Register 
               where (select (Convert (datetime,Payment_Date,103)) as pd 
                      from pat.dbo.Demand_Register)
                  between '"+frmDate1+"' and '"+toDate1+"' ";

和例外:

java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]Syntax error converting datetime from character string.
4

2 回答 2

1

您的陈述不必要的复杂,您可以将其简化为:

String query1="select * from pat.dbo.Demand_Register " +
               "where Convert (datetime,Payment_Date,103) " + 
               "between '"+frmDate1+"' and '"+toDate1+"' ";

但这仍然不是一个好主意。您应该java.sql.Date从 PreparedStatement 构造实例frmDate1toDate1在 PreparedStatement 中使用它们:

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
java.sql.Date from = new java.sql.Date(sdf.parse(frmDate1));
java.sql.Date to = new java.sql.Date(sdf.parse(toDate1));
String query1="select * from pat.dbo.Demand_Register " +
               "where Payment_Date between ? and ?";
PreparedStatement stmt = connection.prepareStatement();
stmt.setDate(1, from);
stmt.setDate(2, to);
ResultSet rs = stmt.executeQuery();

这不仅可以保护您免受 SQL 注入的影响,而且还可以使用潜在的索引来加快速度Payment_Date

于 2012-08-08T19:20:12.103 回答
1

这可能是因为您使用单引号连接字符串,因此也应该使用双引号;看看你的字符串中的组合frmDate1toDate1参数。

所以这应该有效

String query1 = "select * from pat.dbo.Demand_Register where (select  (Convert(datetime,Payment_Date,103)) as pd from pat.dbo.Demand_Register) between '" + frmDate1 + "' and '" + toDate1 + "' ";
于 2012-08-08T05:30:17.220 回答