I'm trying to write a query from java code using SQL to find the difference in years between two date columns. I have a table tblExportHTC
with columns VisitDate
and DateOfBirth
and I want to calculate the number of years between the two columns.
My java code block:
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();
}
Whenever I try to run the code, I get the error
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)
What I want is to get the number of years between columns VisitDate
and DateOfBirth
.
I have found the answer: I have to use TIMESTAMPDIFF()
function instead of DATEDIFF()
and it seems to be working perfectly.
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();
}