我正在尝试使用SQL从Java代码编写查询,以查找两个日期列之间的年份差异。我有一个具有列tblExportHTCVisitDate的表DateOfBirth,并且我想计算两列之间的年数。

我的Java代码块:

 try {
        String path = selectedFiles;
        Connection conn = DriverManager.getConnection("jdbc:ucanaccess://" + path + ";jackcessOpener=app.test.CryptCodecOpener", "", "");
        Statement s = conn.createStatement();
        ResultSet rs = s.executeQuery("SELECT DATEDIFF(year,vis.VisitDate,vis.DateOfBirth) as date_diff "
                + " FROM tblExportHTC vis WHERE vis.ClientCode='PITC-TENT-4-093'");
        while (rs.next()) {
            int visits_count = rs.getInt("date_diff");
            System.err.println("index_pos_from_sexual_partners: " + visits_count);
        }
    } catch (SQLException ex) {
        ex.printStackTrace();
    }


每当我尝试运行代码时,都会出现错误

Caused by: java.sql.SQLSyntaxErrorException: user lacks privilege or object not found: YEAR
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCStatement.fetchResult(Unknown Source)
at org.hsqldb.jdbc.JDBCStatement.executeQuery(Unknown Source)
at net.ucanaccess.jdbc.UcanaccessStatement.executeQuery(UcanaccessStatement.java:216)
Caused by: org.hsqldb.HsqlException: user lacks privilege or object not found: YEAR
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.ExpressionColumn.checkColumnsResolved(Unknown Source)
at org.hsqldb.QueryExpression.resolve(Unknown Source)
at org.hsqldb.ParserDQL.compileCursorSpecification(Unknown Source)
at org.hsqldb.ParserCommand.compilePart(Unknown Source)
at org.hsqldb.ParserCommand.compileStatements(Unknown Source)
at org.hsqldb.Session.executeDirectStatement(Unknown Source)
at org.hsqldb.Session.execute(Unknown Source)


我想要的是获取列VisitDateDateOfBirth之间的年数。

最佳答案

我找到了答案:我必须使用TIMESTAMPDIFF()函数而不是DATEDIFF(),它似乎运行得很好。

try {
    String path = selectedFiles;
    Connection conn = DriverManager.getConnection("jdbc:ucanaccess://" + path + ";jackcessOpener=app.test.CryptCodecOpener", "", "");
    Statement s = conn.createStatement();
    ResultSet rs = s.executeQuery("SELECT TIMESTAMPDIFF(year,vis.VisitDate,vis.DateOfBirth) as date_diff "
            + " FROM tblExportHTC vis WHERE vis.ClientCode='PITC-TENT-4-093'");
    while (rs.next()) {
        int visits_count = rs.getInt("date_diff");
        System.err.println("index_pos_from_sexual_partners: " + visits_count);
    }
} catch (SQLException ex) {
    ex.printStackTrace();
}

10-07 16:02