提问人:caracol 提问时间:11/12/2023 最后编辑:caracol 更新时间:11/12/2023 访问量:47
在 Oracle 中从 JSON 中提取和插入数据
extracting and inserting data from JSON in Oracle
问:
我有一个JSON文件,我正在尝试插入数据库。
插入不起作用,不确定我是否正确循环json
我做了一个非常简单的例子:
下表如下:
CREATE TABLE TEST (
remote_claimid VARCHAR2(20) PRIMARY KEY
);
和程序:
PROCEDURE TEST (
p_json CLOB
) AS
BEGIN
INSERT INTO TEST (
remote_claimid
)
SELECT
remote_claimid
FROM JSON_TABLE(
p_json,
'$.claim[*]'
COLUMNS(
remote_claimid VARCHAR2(20) PATH '$.remote_claimid'
)
);
COMMIT;
exception when others then
log_api.fatal(log_ctx, 'ERROR INSERT_TEST');
raise;
END TEST;
这是 JSON
{claim=[{remote_claimid=5680}, {remote_claimid=7654}]}
这是调用:
json = '{"claim"=[{"remote_claimid"="5680"}, {"remote_claimid"="7654"}]}'
try {
sql.call('{call BILLING_API.TEST(?)}', [json])
output = [SUCCESS: true, msg: "inserts added."]
sql.commit()
} catch(SQLException se) {
sql.rollback()
log.error("Exception: ${se}; Procedure: BILLING_API.TEST; Params: Clob ${responseList}")
output = commonDBService.processException(se)
} finally {
sql.close()
}
没有插入任何内容,没有错误......无 知道发生了什么吗?
谢谢!
答:
1赞
p3consulting
11/12/2023
#1
使用正确的 JSON,您的路径将起作用:
SELECT
remote_claimid
FROM JSON_TABLE(
q'~{"claim" : [{"remote_claimid": 5680}, {"remote_claimid" : 7654}]}~',
'$.claim[*]'
COLUMNS(
remote_claimid VARCHAR2(20) PATH '$.remote_claimid'
)
);
5680
7654
评论
0赞
caracol
11/12/2023
是的。。。但后来......如何将 JSON 传递给函数?也许问题就在那里?
0赞
p3consulting
11/12/2023
应检查remote_claimid列是否包含有效的 JSON:'“claim”=...'不是,'“索赔”:...”是。
0赞
caracol
11/12/2023
伟大!!这就是反应!!我对此进行了更改: responseList = '{“claim”=[{“remote_claimid”=“52680”}, {“remote_claimid”=“76354”}]}' 为此: responseList = '{“claim”:[{“remote_claimid”:“52680”}, {“remote_claimid”:“76354”}]}' 现在它工作了 谢谢!!
0赞
Md Alif Al Amin
11/12/2023
#2
我在你的代码中找不到任何问题。但我建议,你能不能试试这样。我认为这是将json插入oracle数据库的更好方法。
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
public class YourClassName {
public static void main(String[] args) {
String json = "{\"claim\":[{\"remote_claimid\":\"5680\"}, {\"remote_claimid\":\"7654\"}]}";
try (Connection connection = YourDatabaseConnectionProvider.getConnection()) {
// Assuming YourDatabaseConnectionProvider is a class providing a connection to your Oracle database
try (CallableStatement callStmt = connection.prepareCall("{call BILLING_API.TEST(?)}")) {
callStmt.setString(1, json);
callStmt.execute();
// If you need to retrieve output parameters, you can do so here
connection.commit();
System.out.println("Inserts added.");
} catch (SQLException se) {
// Rollback the transaction in case of an exception
connection.rollback();
log.error("Exception: " + se + "; Procedure: BILLING_API.TEST; Params: Clob " + json);
// Handle the exception or delegate it to a method like commonDBService.processException(se)
}
} catch (SQLException e) {
// Handle connection-related exceptions
e.printStackTrace();
}
}
}
希望这段代码对你有所帮助。
评论