将表导入PostgreSQL时如何在CSV值中转义逗号?

时间:2013-03-19 17:05:33

标签: database postgresql csv import

我正在尝试使用'copy'命令将csv文件导入到postgres表中。包含逗号的值已被双引号括起来,但我似乎找不到使用'copy'命令将它们加载到postgres表中而没有任何错误的选项。

我正在使用

'COPY'命令:

CREATE TABLE candidates (Sno int, name varchar, cases int, case_details varchar, .....);
copy candidates from 'something.csv' with NULL AS ' ' csv ;

违规csv行的示例:

1, "some name", 2, "(1):IPC Sections -  147, 323, 352, 504, 506 , Other Details - Case no.283A/2000, A.C.J.M-5, Ghumangunj Ellahabad, UP, Dt.12.11.2000", .....

case_details属性上方的值中包含逗号。这是我的问题。

3 个答案:

答案 0 :(得分:3)

适合我(PG 9.2,linux):

$ cat something.csv 
1, "some name", 2, "(1):IPC Sections -  147, 323, 352, 504, 506 , Other Details - Case no.283A/2000, A.C.J.M-5, Ghumangunj Ellahabad, UP, Dt.12.11.2000"

$ psql test
test=> CREATE TABLE candidates (Sno int, name varchar, cases int, case_details varchar);
CREATE TABLE
test=> \copy candidates from 'something.csv' with NULL AS ' ' csv ;
test=> select * from candidates ;
 sno |    name    | cases |                                                             case_details                                                             
-----+------------+-------+--------------------------------------------------------------------------------------------------------------------------------------
   1 |  some name |     2 |  (1):IPC Sections -  147, 323, 352, 504, 506 , Other Details - Case no.283A/2000, A.C.J.M-5, Ghumangunj Ellahabad, UP, Dt.12.11.2000
(1 row)

答案 1 :(得分:1)

可能的解决方案 - 用引号替换任何其他字符的逗号,加载数据,替换逗号。

答案 2 :(得分:0)

PhpPgAdmin工具不够智能,无法处理逗号。 Postgres非常聪明,可以处理它们。它首先使用逗号从导入的文件中拆分给定行中的数据,然后它会自动在值后面添加引号。所以没有办法与客户端一起做。至少在5.1版本中就是这种情况。他们可能已在以后的版本中修复它。

因此,如果您从PhpPgAdmin工具导入,请将逗号替换为“;”或者与您的数据分开的东西,然后在导入后运行SQL查询来修复。

相关问题