暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

PostgreSQL和MogDB使用copy导入存在多余数据的文件

由迪 2024-03-25
1117

原作者:茹跃涵

问题概述

使用copy导入CSV文件时,报错“ERROR: extra data after last expected column”,文件格式没问题的情况下,csv数据文件的列数比表实际列数多时也会出现该报错

例如:

[postgres@mydb1a ~]$ cat test.csv
id1,id3,id4,temp
1,2,3,4
pg
postgres=# \copy  test(id1,id3,id4) from test.csv with(format 'csv',header)
ERROR:  extra data after last expected column
CONTEXT:  COPY test, line 2: "1,2,3,4"
mogdb
MogDB=#\copy test from test.csv (format 'csv',header 'on');
ERROR:  extra data after last expected column
CONTEXT:  COPY test, line 2: "1,2,3,4"
解决方案
pg

可以使用cut命令截取需要的列

解释[postgres@mydb1a ~]$ cut  -f 1-3 -d ','  test.csv>test1.csv
[postgres@mydb1a ~]$ cat test1.csv
id1,id3,id4
1,2,3

再导入就没问题了

解释postgres=# \copy  test(id1,id3,id4) from test1.csv with(format 'csv',header)
COPY 1
postgres=# select * from test;
 id1 | id3 | id4
-----+-----+-----
   1 | 2   |   3
(1 row)
mogdb

mogdb中copy导入时可以使用"IGNORE_EXTRA_DATA"选项,忽略多出的列

IGNORE_EXTRA_DATA
若数据源文件比外表定义列数多,是否会忽略对多出的列。该参数只在数据导入过程中使用。
取值范围:true/on、false/off。
解释MogDB=#\copy test from test.csv (format 'csv',header 'on',IGNORE_EXTRA_DATA 'on')
MogDB=#select * from test;
MogDB=# id1 | id3 | id4 
-----+-----+-----
   1 |   2 |   3
(1 row)

尤其是数据列内容包含分隔符时,cut命令做截取不方便,但mogdb中使用copy导入同样没问题

解释omm@modb:~$ cat test.csv 
id1,id3,id4,temp
1,"2,3",3,4

omm@modb:~$ cut -f 1-3 -d ',' test.csv 
id1,id3,id4
1,"2,3"
##数据列中包含分隔符时,按之前的cut方法,截取的列不准确

MogDB=#\copy test1 from test.csv (format 'csv',header 'on',IGNORE_EXTRA_DATA 'on')
MogDB=#select * from test1;
 id1 | id3 | id4 
-----+-----+-----
   1 | 2,3 |   3
注意

mogdb中copy导入时使用"IGNORE_EXTRA_DATA"选项时,如果行尾换行符丢失,使两行变成一行时,设置此参数为true将导致后一行数据被忽略掉。

参考

docs.mogdb.io/zh/mogdb/v5.0/COPY/#功能描述

「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

文章被以下合辑收录

评论