jdbc query - 日期范围作为参数

时间:2010-03-17 06:16:34

标签: java sql postgresql jdbc

我想编写一个JDBC语句,它可以处理任意数量的NOT BETWEEN date1 AND date2 where子句。

通过单个查询,我的意思是相同的SQL字符串将用于创建JDBC语句,然后提供不同的参数。

这样底层框架可以有效地缓存查询(之前我已被它蜇过)。

基本上,我想找到一个等同于

的查询
SELECT * FROM table WHERE mydate NOT BETWEEN ? AND ?
    AND mydate NOT BETWEEN ? AND ?
    AND mydate NOT BETWEEN ? AND ?
    AND mydate NOT BETWEEN ? AND ?

同时可以使用更少的参数:

SELECT * FROM table WHERE mydate NOT BETWEEN ? AND ?

或更多参数

SELECT * FROM table WHERE mydate NOT BETWEEN ? AND ?
    AND mydate NOT BETWEEN ? AND ?
    AND mydate NOT BETWEEN ? AND ?
    AND mydate NOT BETWEEN ? AND ?
    AND mydate NOT BETWEEN ? AND ?
    AND mydate NOT BETWEEN ? AND ?

如果更简单,效率更高,我会考虑使用临时表。

感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

准备好的陈述具有固定数量的参数。在某些情况下(比如IN())你可以使用数组来解决这个问题,但在你的情况下这不会起作用。

当临时表具有列“startdate”和“enddate”时,临时表将执行该操作,只需加入ON(mydate BETWEEN startdate AND enddate)。从临时表中插入和删除行会更改参数的数量。

答案 1 :(得分:2)

您只需动态生成SQL字符串即可。 E.g。

public List<Data> find(List<BetweenDate> betweenDates) throws SQLException {
    StringBuilder sql = new StringBuilder("SELECT * FROM table WHERE ");
    for (int i = 0; i < betweenDates.size();) {
        sql.append("mydate NOT BETWEEN ? AND ?");
        if (++i < betweenDates.size()) sql.append(" AND ");
    }

    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet resultSet = null;
    List<Data> result = new ArrayList<Data>();

    try {
        connection = database.getConnection();
        statement = connection.prepareStatement(sql.toString());
        for (int i = 0; i < betweenDates.size(); i++) {
            preparedStatement.setObject((i * 2) + 1, betweenDates.get(i).getStartDate());
            preparedStatement.setObject((i * 2) + 2, betweenDates.get(i).getEndDate());
        }
        resultSet = statement.executeQuery();
        // ...