我们正在使用 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 ,?)
但是有没有更好的方法来进行转换,因为这似乎不是一个好的解决方案,因为有很多查询需要修改,而且还可能存在其他此类转换问题。
是否有一些参数可以在数据库级别设置以执行自动转换?
最佳答案
我们在这里找到了答案
应该添加一个新的连接属性:
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/