Skip to content

Commit

Permalink
fix(jdbc): add fallback to LocalDateTime.parse in ResultSet#getObject
Browse files Browse the repository at this point in the history
  • Loading branch information
gotson committed Oct 18, 2023
1 parent a8c4b97 commit 22b27c6
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/main/java/org/sqlite/jdbc4/JDBC4ResultSet.java
Original file line number Diff line number Diff line change
Expand Up @@ -345,9 +345,14 @@ public <T> T getObject(int columnIndex, Class<T> type) throws SQLException {
}
}
if (type == LocalDateTime.class) {
Timestamp timestamp = getTimestamp(columnIndex);
if (timestamp != null) return type.cast(timestamp.toLocalDateTime());
else return null;
try {
Timestamp timestamp = getTimestamp(columnIndex);
if (timestamp != null) return type.cast(timestamp.toLocalDateTime());
else return null;
} catch (SQLException e) {
// If the FastDateParser failed, try parse it with LocalDateTime.
return type.cast(LocalDateTime.parse(getString(columnIndex)));
}
}

int columnType = safeGetColumnType(markCol(columnIndex));
Expand Down
25 changes: 25 additions & 0 deletions src/test/java/org/sqlite/QueryTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
Expand Down Expand Up @@ -103,6 +106,28 @@ public void dateTimeTest() throws Exception {
stmt.setDate(1, new java.sql.Date(now.getTime()));
}

@Test
public void jdk8LocalDateTimeTest() throws Exception {
Connection conn = getConnection();

conn.createStatement().execute("create table sample (d1 date, d2 time, d3 datetime)");

LocalDateTime dateTime = LocalDateTime.of(2022, 1, 1, 12, 25, 15);
try (PreparedStatement stmt = conn.prepareStatement("insert into sample values(?, ?, ?)")) {
stmt.setObject(1, dateTime.toLocalDate());
stmt.setObject(2, dateTime.toLocalTime());
stmt.setObject(3, dateTime);
stmt.executeUpdate();
}

try (ResultSet rs = conn.createStatement().executeQuery("select * from sample")) {
assertThat(rs.next()).isTrue();
assertThat(rs.getObject(1, LocalDate.class)).isEqualTo(dateTime.toLocalDate());
assertThat(rs.getObject(2, LocalTime.class)).isEqualTo(dateTime.toLocalTime());
assertThat(rs.getObject(3, LocalDateTime.class)).isEqualTo(dateTime);
}
}

@Test
public void dateTimeWithTimeZoneTest() throws Exception {
Properties properties = new Properties();
Expand Down

0 comments on commit 22b27c6

Please sign in to comment.