我想创建一个数据库来使用此代码将外汇汇率存储到 PostgreSQL 中:
RestTemplate restTemplate = new RestTemplate();
String url = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml";
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
System.out.println(response.getBody());
我不确定 wat 表结构应该是最好的选择。目前我能想到的唯一模型是:
货币 | 率 | 日期 |
---|---|---|
欧元 | 1.21 | 2011-11-2 |
日元 | 2.11 | 2011-11-2 |
英镑 | 1.3 | 2011-11-2 |
CAD | 2.1 | 2011-11-2 |
欧元 | 1.21 | 2012-11-2 |
日元 | 2.11 | 2012-11-2 |
英镑 | 1.3 | 2012-11-2 |
CAD | 2.1 | 2012-11-2 |
使用例如将 XML 文件直接存储到数据库中更好还是有更好更优化的方法?
您提供的表结构有效地捕获了 XML 响应中元素的内容。以下代码演示了一种使用
curl
检索当前每日汇率并使用 XMLTABLE
处理返回的 XML 的方法。
最好不要使用 SQL 关键字作为列标识符,因此日期存储为
exchange_date
:
CREATE TABLE IF NOT EXISTS exchange_rates (
exchange_date DATE,
currency TEXT,
rate NUMERIC,
PRIMARY KEY (exchange_date, currency)
);
以下 SQL 从 URL 检索每日汇率并将其插入到
exchange_rates
:
-- ensure that there is a temporary table to hold the response from the URL
CREATE TEMPORARY TABLE IF NOT EXISTS forex_response (
id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
response_line TEXT
);
-- ensure that any prior responses have been cleared
TRUNCATE TABLE forex_response;
-- use an external program to read from the URL (the delimiter was chosen
-- to minimize the risk of inadvertently splitting a response line into
-- multiple columns)
COPY forex_response (response_line)
FROM PROGRAM 'curl https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml'
WITH (FORMAT TEXT, DELIMITER E'\01');
WITH
-- convert the response lines into an XML document
x AS (SELECT STRING_AGG(response_line, '' ORDER BY id)::XML AS response
FROM forex_response)
INSERT INTO exchange_rates(exchange_date, currency, rate)
SELECT
r.exchange_date, r.currency, r.rate
FROM
XMLTABLE(
XMLNAMESPACES (
'http://www.gesmes.org/xml/2002-08-01' AS gesmes,
'http://www.ecb.int/vocabulary/2002-08-01/eurofxref' AS b
),
'/gesmes:Envelope/b:Cube/b:Cube/b:Cube'
PASSING (SELECT x.response FROM x)
COLUMNS
rate NUMERIC PATH '@rate',
exchange_date DATE PATH '../@time',
currency TEXT PATH '@currency') r
ON CONFLICT DO NOTHING;
要使用历史值而不是当天的值填充
exchange_rates
,请使用以下 URL:
https://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist.xml
https://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist-90d.xml
这些 URL 返回所有可用的历史值,或仅返回过去 90 天的历史值(分别)。