postgres 将字符串插入数字列 - 不会发生自动类型转换
postgres insert string to numeric column - auto-typecast does not happen
postgres DB test1 中有一个 table 具有模式:
我们正在使用 spring 框架 jdbcTemplate 来插入数据,如下所示:
Object[] params = {"978","tour"};
jdbcTemplate.update("insert into test1 values (?,?)", params);
但这给出了例外:
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 ,?)
但是有没有更好的方法来进行转换,因为这似乎不是一个好的解决方案,因为有很多查询需要修改,而且还可能存在其他此类转换问题。
是否有一些参数可以在数据库级别设置以执行自动转换?
是的,在这里去掉双引号:
Object[] params = {"978","tour"};
变成
Object[] params = {978,"tour"};
或者按照您提到的进行转换。
我们在这里找到了答案
Storing json, jsonb, hstore, xml, enum, ipaddr, etc fails with "column "x" is of type json but expression is of type character varying"
应添加新的连接属性:
字符串 url = "jdbc:postgresql://localhost/test";
属性 props = new Properties();
props.setProperty("user","fred");
props.setProperty("password","secret");
props.setProperty("stringtype", "unspecified");
连接conn = DriverManager.getConnection(url, props);
https://jdbc.postgresql.org/documentation/94/connect.html
"如果 stringtype 设置为未指定,参数将作为未类型化的值发送到服务器,并且服务器将尝试推断适当的类型。如果您有一个现有的应用程序,这将很有用使用 setString() 来设置实际上是其他类型的参数,例如整数,并且您无法更改应用程序以使用适当的方法,例如 setInt()"
postgres DB test1 中有一个 table 具有模式:
我们正在使用 spring 框架 jdbcTemplate 来插入数据,如下所示:
Object[] params = {"978","tour"};
jdbcTemplate.update("insert into test1 values (?,?)", params);
但这给出了例外:
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 ,?)
但是有没有更好的方法来进行转换,因为这似乎不是一个好的解决方案,因为有很多查询需要修改,而且还可能存在其他此类转换问题。
是否有一些参数可以在数据库级别设置以执行自动转换?
是的,在这里去掉双引号:
Object[] params = {"978","tour"};
变成
Object[] params = {978,"tour"};
或者按照您提到的进行转换。
我们在这里找到了答案
Storing json, jsonb, hstore, xml, enum, ipaddr, etc fails with "column "x" is of type json but expression is of type character varying"
应添加新的连接属性:
字符串 url = "jdbc:postgresql://localhost/test";
属性 props = new Properties();
props.setProperty("user","fred");
props.setProperty("password","secret");
props.setProperty("stringtype", "unspecified");
连接conn = DriverManager.getConnection(url, props);
https://jdbc.postgresql.org/documentation/94/connect.html
"如果 stringtype 设置为未指定,参数将作为未类型化的值发送到服务器,并且服务器将尝试推断适当的类型。如果您有一个现有的应用程序,这将很有用使用 setString() 来设置实际上是其他类型的参数,例如整数,并且您无法更改应用程序以使用适当的方法,例如 setInt()"