如何在sql查询中将字符串转换为日期?

时间:2012-08-08 05:08:02

标签: java sql sql-server jdbc

我正在使用MS-SQL Server。我在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.

2 个答案:

答案 0 :(得分: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 + "' ";

答案 1 :(得分:1)

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

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

但这仍然不是一个好主意。您应该从java.sql.DatefrmDate1构建toDate1个实例,并在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上的潜在索引。