当前位置: 首页 > 知识库问答 >
问题:

java.sql.sqlsyntaxerrorexception:用户缺乏权限或未找到对象:年

皇甫树
2023-03-14

我试图使用SQL从java代码编写一个查询,以查找两个日期列之间的年份差异。我有一个表tblexporthtc,其中包含列visitdatedateofborny,我想计算这两列之间的年数。

我的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)

我想要的是获得列visitdatedateofborny之间的年数。

共有1个答案

濮俊美
2023-03-14

我已经找到了答案:我必须使用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();
}
 类似资料: