目前还不清楚您需要如何处理这些数据。如果您确实需要完全在数据库中处理它(看起来像是您最喜欢的脚本语言的任务),一种选择是使用hstore
.
一条一条地转换记录很容易:
假设
%s = BundleSize,155648,DynamicSize,204800,标识符,com.URLConnectionSample,名称,URLConnectionSample,ShortVersion,1.0,Version,1.0
SELECT * FROM each(hstore(string_to_array(%s, ',')));
输出:
key | value
--------------+-------------------------
Name | URLConnectionSample
Version | 1.0
BundleSize | 155648
Identifier | com.URLConnectionSample
DynamicSize | 204800
ShortVersion | 1.0
如果您的表中的列与字段名称完全匹配(请注意引号,populate_record
对键名区分大小写):
CREATE TABLE data (
"BundleSize" integer, "DynamicSize" integer, "Identifier" text,
"Name" text, "ShortVersion" text, "Version" text);
您可以hstore
像这样将记录插入其中:
INSERT INTO data SELECT * FROM
populate_record(NULL::data, hstore(string_to_array(%s, ',')));
如果您有多个记录的逗号分隔值,事情会变得更加复杂。
%s = BundleSize,155648,DynamicSize,204800,Identifier,com.URLConnectionSample,Name,URLConnectionSample,ShortVersion,1.0,Version,1.0,BundleSize,155648,DynamicSize,16384,Identifier,com.IdentifierForVendor3,Name,IdentifierForVendor3,ShortVersion,1.0 ,版本,1.0,
您需要首先将数组分解为number_of_fields * 2 = 12
元素块。
SELECT hstore(row) FROM (
SELECT array_agg(str) AS row FROM (
SELECT str, row_number() OVER () AS i FROM
unnest(string_to_array(%s, ',')) AS str
) AS str_sub
GROUP BY (i - 1) / 12) AS row_sub
WHERE array_length(row, 1) = 12;
输出:
"Name"=>"URLConnectionSample", "Version"=>"1.0", "BundleSize"=>"155648", "Identifier"=>"com.URLConnectionSample", "DynamicSize"=>"204800", "ShortVersion"=>"1.0"
"Name"=>"IdentifierForVendor3", "Version"=>"1.0", "BundleSize"=>"155648", "Identifier"=>"com.IdentifierForVendor3", "DynamicSize"=>"16384", "ShortVersion"=>"1.0"
并将其插入上述表中:
INSERT INTO data SELECT (populate_record(NULL::data, hstore(row))).* FROM ...
查询的其余部分是相同的。