【问题标题】:HSQLDB, LocalDateTime, JdbcTemplateHSQLDB、LocalDateTime、JdbcTemplate
【发布时间】:2018-01-03 19:54:57
【问题描述】:

我正在尝试将 HSQLDB 与 spring JDBC 模板一起使用。它工作正常,直到我使用 Java 8 的 LocalDateTime 类。

我有这个代码:

import org.hsqldb.jdbc.JDBCDataSource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;

import java.time.LocalDateTime;

    public class Test
    {
        public static void main(String[] args) throws Exception
        {
            JDBCDataSource dataSource = new JDBCDataSource();
            dataSource.setUser("SA");
            dataSource.setPassword("");
            dataSource.setUrl("jdbc:hsqldb:mem:db");

            Resource resource = new ClassPathResource("/test.sql");
            ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(resource);
            databasePopulator.execute(dataSource);

            JdbcTemplate template = new JdbcTemplate(dataSource);
            template.update("INSERT INTO test VALUES (?)",  LocalDateTime.now());
        }
    }

脚本如下所示:

CREATE TABLE test
(
  datetime DATETIME NOT NULL,
);

当我尝试运行它时,我会得到异常:

org.hsqldb.HsqlException: incompatible data type in conversion

在应用后端,我使用 LocalDateTime。我怎样才能使这项工作?

【问题讨论】:

    标签: java hsqldb jdbctemplate


    【解决方案1】:

    您应该能够通过使用Timestamp.valueOf()LocalDateTime 转换为java.sql.Timestamp 来解决此问题:

    JdbcTemplate template = new JdbcTemplate(dataSource);
    template.update("INSERT INTO test VALUES (?)",  Timestamp.valueOf(LocalDateTime.now()));
    

    【讨论】:

    • 谢谢,它有效。使用 MySQL,它甚至可以使用 LocalDateTime :)
    • 我用LocalDate 解决了类似的问题。我用过java.sql.Date.valueOf()。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 2016-04-10
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 2017-03-22
    • 2011-11-28
    相关资源
    最近更新 更多