【问题标题】:Why h2 database have data conversion error converting为什么h2数据库有数据转换错误转换
【发布时间】:2021-06-10 23:44:56
【问题描述】:

我的 h2 数据库有问题。

我尝试像这样进入数据库的值

INSERT INTO INGREDIENT(id,name,type) values ('FLTO','pszenna','WRAP');

然后我得到了这个错误

数据转换错误转换“'WRAP' (INGREDIENT: ""TYPE"" INTEGER)"; SQL语句:

当我做某事时,我的查询正在工作

INSERT INTO INGREDIENT(id,name,type) values ('FLTO','pszenna','3');

但在 schema.sql 文件中,类型字段是 varchar,所以为什么这不起作用

create table if not exists Ingredient (
  id varchar(4) not null,
  name varchar(40) not null,
  type varchar(10) not null
);

【问题讨论】:

  • H2 认为您的 type 列是一个整数,并且它抱怨它无法将 'WRAP' 转换为整数。第二个示例有效,因为 '3' 可以转换为 3
  • 好吧,我知道这一点,但我创建了一个像 varchar 而不是 int 这样的字段类型,所以这应该可以工作
  • 验证createinsert应用于同一个数据库;追加;IFEXISTS=TRUE,如图here,以避免创建虚假数据库文件。
  • 尝试删除并重新创建表。您可能仍然有一个较旧的架构,并且“如果存在则创建表”最终什么都不做。

标签: java spring database h2


【解决方案1】:

好的,所以我认为问题出在数据库上,因为当我想要时

DROP TABLE 成分;

找不到错误表“Ingrdient”。

这是我的 application.properties 文件

# Enabling H2 Console
spring.h2.console.enabled=true

# Custom H2 Console URL
spring.h2.console.path=/h2
spring.datasource.url=jdbc:h2:mem:testdb

我应该怎么做

【讨论】:

  • H2 内存数据库有点棘手,因为它们会在您关闭最后一个连接时消失。如果您将网址更改为 spring.datasource.url=jdbc:h2:file:mydb 之类的内容,您可能会得到更好的结果。
  • 另一种解决方法是将;DB_CLOSE_DELAY=-1 添加到jdbc url,如下所示:spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1
【解决方案2】:

我尝试使用代码(使用 Spring 的 JdbcTemplate)重现您的错误,但它运行成功:

@Test
public void testH2() {
    JdbcDataSource ds = new JdbcDataSource();
    ds.setUrl("jdbc:h2:file:/tmp/test123");
    JdbcTemplate jdbc = new JdbcTemplate(ds);
    jdbc.update("drop table if exists ingredient");
    jdbc.update(
            "create table if not exists ingredient(" +
            " id varchar(4) not null," +
            " name varchar(40) not null," +
            " type varchar(10) not null)"); // if this is " type int)" I get the same error message
    jdbc.update("delete from ingredient");
    showTable(jdbc, "empty");
    jdbc.update("insert into ingredient(id,name,type) values ('FLTO','pszenna','3')");
    showTable(jdbc, "added FLTO");
    jdbc.update("insert into ingredient(id,name,type) values ('FLTW','pszennb','WRAP')");
    showTable(jdbc, "added FLTW");
}

void showTable(JdbcTemplate jdbc, String message) {
    System.out.println("=== " + message + " ===");
    jdbc.query("select id, name, type from ingredient order by id", rs -> {
        int n = 0;
        while (rs.next()) {
            System.out.println("id=" + rs.getString(1) + " name=" + rs.getString(2) + " type=" + rs.getString(3));
            n++;
        }
        System.out.println(n + " rows");
        return n;
    });
}

如果我将type 的类型更改为int,我会收到与您完全相同的错误消息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-13
    • 2020-09-14
    • 2016-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    相关资源
    最近更新 更多