java.sql.SQLSyntaxErrorException:用户缺少特权或找不到对象:YEAR

时间:2018-08-08 11:53:43

标签: java sql ms-access ucanaccess

我正在尝试使用SQL从Java代码编写查询,以查找两个日期列之间的年份差异。我有一个表格tblExportHTC,其中有列VisitDateDateOfBirth,我想计算两列之间的年数。

我的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列之间的年数。

1 个答案:

答案 0 :(得分:1)

我找到了答案:我必须使用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();
}