如何在准备好的查询语句之间使用

时间:2017-10-12 06:37:02

标签: sql

例如,如果我们必须从两个特定日期之间的表中找到一些数据,我们就像这样编写查询:

Select * from TableName where Date lies between '01-01-2000' and '01-01-2002'

我只想知道如何在PreparedQueryStatement中使用此查询?

1 个答案:

答案 0 :(得分:1)

您需要使用带占位符的字符串,然后将java.sql.Date的实例传递给PreparedStatement

String query = "Select * from TableName where some_date_column between ? and ?";
java.sql.Date dateOne = java.sql.Date.valueOf(LocalDate.of(2000, 1, 1));
java.sql.Date dateTwo = java.sql.Date.valueOf(LocalDate.of(2002, 1, 1));

PreparedStatement pstmt = connection.prepareStatement(query);
pstmt.setDate(1, dateOne);
pstmt.setDate(2, dateTwo);
ResultSet rs = pstmt.executeQuery();
... process the result ...

从不将日期(或时间戳或数字)作为字符串传递!

请注意,SQL BETWEEN运算符包含这两个值。表达式

some_date_column BETWEEN date '2000-01-01' and date '2002-01-01'

相当于:

    some_date_column >= date '2000-01-01' 
and some_date_column <= date '2002-01-01'

如果您想要从'2002-01-01'排除行,则需要:

some_date_column BETWEEN date '2000-01-01' and date '2001-12-31'