【问题标题】:SQLite 'BETWEEN' doesn't behave as expectedSQLite 'BETWEEN' 的行为不符合预期
【发布时间】:2012-10-23 14:57:51
【问题描述】:

我正在尝试选择介于两列值之间的所有行。这些值是 UNIX 时间戳,但查询根本不返回任何行。为什么会这样?

这是我的代码:

public static ArrayList<Appointment> getAppointments(long start, long end) {
    ArrayList<Appointment> appointments = new ArrayList<>();
    try {
        Statement stat = db.createStatement();
        System.out.println("\n" + start + "  ->  " + end);

        // debugging only
        try (ResultSet rs = stat.executeQuery("SELECT * FROM appointments;")) {
            while (rs.next()) {
                long time = rs.getLong("date");
                if (time >= start && time <= end) {
                    System.out.println("Should be adding to list");
                }
            }
        } // 

        try (ResultSet rs = stat.executeQuery("SELECT * FROM appointments WHERE date BETWEEN " + start + " AND " + end + ";")) {
            while (rs.next()) {
                System.out.println("ADDING");
                appointments.add(new Appointment(rs.getLong("date"), rs.getInt("duration")));
            }
        }
    } catch (SQLException ex) {
    }
    System.out.println(appointments);
    return appointments;
}

表中包含这些值的三行:

1347390000000 15
1347461100000 30
1347469200000 45

输出是:

date = 1347390000000 duration = 15
date = 1347461100000 duration = 30
date = 1347469200000 duration = 45

1350141222283  ->  1350746022283
[]

1349536422283  ->  1350141222283
[]

1348931622283  ->  1349536422283
[]

1348330422283  ->  1348931622283
[]

1347725622283  ->  1348330422283
[]

1347120822283  ->  1347725622283
Should be adding to list
Should be adding to list
Should be adding to list
[]

1346516022283  ->  1347120822283
[]

【问题讨论】:

  • 你在盲目地捕捉你的 SQLExceptions。不要那样做。放置一些代码,至少可以报告它们是什么。
  • 我省略了 catch 代码,因为它与问题无关。至于输出,据我所知,这是完全合理的。 [] 是每次搜索范围更改(每周)时该方法返回的内容。
  • +1 回到问题,我不太确定发生了什么,因为该查询适用于 SQL Fiddle sqlfiddle.com/#!5/bd4d0/1
  • 现在一切都是 System.out,因为 out 和 err 不同步,这就是顺序混乱的原因。对此表示歉意。 :) 有趣的是它适用于 SQL Fiddle,我觉得这是我在某处遗漏的一个小细节。
  • 也许数据库中没有定义“日期”列?这可能会导致意外行为。

标签: java sqlite jdbc


【解决方案1】:

你必须声明列的数据类型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-27
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    • 2021-04-09
    相关资源
    最近更新 更多