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

Ann*_*Ann 3 database postgresql casting jdbctemplate

postgres DB test1中有一个表有架构:在此输入图像描述

我们使用spring框架jdbcTemplate来插入数据如下:

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

jdbcTemplate.update("insert into test1 values (?,?)", params);
Run Code Online (Sandbox Code Playgroud)

但这给出了例外:

org.springframework.jdbc.BadSqlGrammarException:PreparedStatementCallback; 错误的SQL语法[插入test1值(?,?)]; 嵌套异常是org.postgresql.util.PSQLException:错误:列"id"的类型为整数,但表达式的类型为字符变化 ERROR:列"id"的类型为整数但表达式的类型为字符变化

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

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

解决方法是显式转换:

insert into test1 values (?::numeric ,?)
Run Code Online (Sandbox Code Playgroud)

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

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

Ann*_*Ann 7

我们在这里找到了答案

存储json,jsonb,hstore,xml,enum,ipaddr等失败,"column"x"的类型为json,但表达式的类型字符不同"

应添加新的连接属性:

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

属性props = new Properties();

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

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

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

Connection conn = DriverManager.getConnection(url,props);

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

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