使用PostgreSQL时,使用COPY命令处理错误

时间:2021-01-31 12:26:42

I have a Python script that is executing the following command to copy the content of a CSV file to a database:

我有一个Python脚本执行以下命令将CSV文件的内容复制到数据库:

copy_query = "COPY table_name FROM STDIN DELIMITER '%s' CSV HEADER QUOTE '\"';" % (self.delimiter)

table_name represents an already created table with specific types. The data in the CSV file doesn't always match with the column type. For example, the CSV file could be like this:

table_name表示已创建的具有特定类型的表。 CSV文件中的数据并不总是与列类型匹配。例如,CSV文件可能如下所示:

"row1", 123, "2012-11-11"
"row2", 346, "2012-11-12"
"row3", \N,  "2012-11-12"

As you can see, column 2 should be of type int, but since the data on row 3 doesn't match with type int, the entire operation fails. Is there a way to maybe reject this row altogether? I'd prefer it to fill in with some default value of the appropriate type, but rejecting the row outright is fine too. Thank you for your help!

如您所见,第2列应为int类型,但由于第3行上的数据与int类型不匹配,因此整个操作将失败。有没有办法可以完全拒绝这一行?我更喜欢用相应类型的一些默认值填写,但是完全拒绝该行也很好。感谢您的帮助!

1 个解决方案

#1


0  

You cannot do this with COPY command but you could modify the target table to accept NULL for these numeric fields.

您不能使用COPY命令执行此操作,但您可以修改目标表以接受这些数字字段的NULL。

#1


0  

You cannot do this with COPY command but you could modify the target table to accept NULL for these numeric fields.

您不能使用COPY命令执行此操作,但您可以修改目标表以接受这些数字字段的NULL。