database - postgres 将字符串插入数字列 - 不会发生自动类型转换

标签 database postgresql casting jdbctemplate

postgres DB test1 中有一个表具有模式:enter image description here

我们正在使用 spring 框架 jdbcTemplate 来插入数据,如下所示:

Object[] params = {"978","tour"};

jdbcTemplate.update("insert into test1 values (?,?)", params);

但这给出了异常(exception):

org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [insert into test1 values (?,?)]; nested exception is org.postgresql.util.PSQLException: ERROR: column "id" is of type integer but expression is of type character varying ERROR: column "id" is of type integer but expression is of type character varying

这通过隐式类型转换适用于 Oracle 数据库,但 postgres 似乎不能那样工作。

这可能是 postgres 驱动程序的问题吗?

解决方法是显式转换:

insert into test1 values (?::numeric ,?)

但是有没有更好的方法来进行转换,因为这似乎不是一个好的解决方案,因为有很多查询需要修改,而且还可能存在其他此类转换问题。

是否有一些参数可以在数据库级别设置以执行自动转换?

最佳答案

我们在这里找到了答案

Storing json, jsonb, hstore, xml, enum, ipaddr, etc fails with "column "x" is of type json but expression is of type character varying"

应该添加一个新的连接属性:

String url = "jdbc:postgresql://localhost/test";

属性 props = new Properties();

props.setProperty("用户","fred");

props.setProperty("密码"," secret ");

props.setProperty("stringtype", "unspecified");

连接conn = DriverManager.getConnection(url, props);

https://jdbc.postgresql.org/documentation/94/connect.html

"如果 stringtype 设置为未指定,参数将作为未类型化的值发送到服务器,并且服务器将尝试推断适当的类型。如果您有一个使用 setString() 的现有应用程序,这将很有用设置实际上是其他类型的参数,例如整数,并且您无法更改应用程序以使用适当的方法,例如 setInt()"

关于database - postgres 将字符串插入数字列 - 不会发生自动类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36883965/

相关文章:

ruby-on-rails - Rails 5 按 belongs_to 协会分组

c# - 无法使用扩展方法隐式转换类型

database - JPA - 左连接 2 个没有关联的表

c - C 语言的 postgresQL 扩展函数(从 v8.0x 到 v9.0 有什么变化)?

php - CakePHP saveAll() 函数问题

postgresql - 如何使用 postgres 在 GKE kubernetes StatefulSet 中保留数据?

swift - 你能检查一个类型(不是实例)是否是另一个类型的子类?

java - Java从Excel中获取文本框的值

mysql - Select value that does not exist in the another column of the same table, MySQL Database Not Exists 子句

c# - DataSelect导致错误DataSelect接受3个参数