gpt4 book ai didi

java - 如何将数据持久保存到 postgres,而无需转换特定的数据类型

转载 作者:行者123 更新时间:2023-12-01 09:19:41 25 4
gpt4 key购买 nike

在我的 spring-boot 应用程序中,我从 API 接收 json 数据,并且我需要在没有强类型对象的情况下保留这些数据。

目前,我的代码结构如下:

String sql = "INSERT INTO problem " + "(name, favorite_number, favorite_color) VALUES (?, ?, ?)";

PreparedStatement ps = c.prepareStatement(sql);

int counter = 1;
while( keys2.hasNext() ) {
String key = (String)keys2.next();

ps.setObject(counter, dataValues.get(key));
counter ++;
}

ps.executeUpdate();
ps.close();

目标postgres表的结构是:

name:  string
favorite_number: int
favorite_color: string

其中 dataValues 是 JSONObject:

JSONObject dataValues = (JSONObject) configParameters.get(2);

Iterator<?> keys = dataValues.keys();

JDBC 驱动程序失败并显示以下消息:

org.postgresql.util.PSQLException: ERROR: column "favorite_number" is of type integer but expression is of type character varying
Hint: You will need to rewrite or cast the expression.

有没有办法以不需要显式类型转换的方式创建此 INSERT 语句?

最佳答案

JDBC 对准备语句中使用的类型非常严格。

绕过该问题的一种方法是使用 PreparedStatement 变量的元数据来检索与每个动态参数关联的类型。
在您的情况下,如果其中之一是数字,您可以使用 Integer.ValueOf(dataValues.get(key))< 返回的整数执行 ps.setInt(...)/

您可以调用 ps.getParameterMetaData() 来检索 ParameterMetaData 实例。
然后,您可以从该实例调用 getParameterType(int param)getParameterTypeName(int param) 来检索参数类型。对两者进行测试,看看哪一个更合适。

不幸的是,它不确定它是否有效,因为根据 DBMS,这些元数据实用程序或多或少都得到了很好的实现......
即使有效,也是有代价的。

<小时/>

java.sql.ParameterMetaData

An object that can be used to get information about the types and properties for each parameter marker in a PreparedStatement object. For some queries and driver implementations, the data that would be returned by a ParameterMetaData object may not be available until the PreparedStatement has been executed.

Some driver implementations may not be able to provide information about the types and properties for each parameter marker in a CallableStatement object.

不要犹豫,提出反馈:)

关于java - 如何将数据持久保存到 postgres,而无需转换特定的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40248417/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com