用于加载数据的Python psycopg2 copy_from()会为空整数值引发错误:DataError:整数的无效输入语法:“” [英] Python psycopg2 copy_from() to load data throws error for null integer values: DataError: invalid input syntax for integer: ""

查看:659
本文介绍了用于加载数据的Python psycopg2 copy_from()会为空整数值引发错误:DataError:整数的无效输入语法:“”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用psycopg2的copy_from()方法将python的StringIO对象中的数据加载到Postgres数据库表中。

I am trying to load data from a StringIO object of python into a Postgres database table using psycopg2's copy_from() method.

我的copy_from在第一个记录本身失败专门针对具有空值(,不带引号)的特定(可为空)整数列。我还尝试使用Python的None关键字代替NULL代替。
它引发了以下错误:
DataError:整数的无效输入语法:
上下文:COPY,第1行,列:

My copy_from fails on the first record itself specifically for a particular (nullable) integer column which has null value ('' without quotes). I have also tried using Python's None keyword instead of '' for NULL values. It throws me the following error: DataError: invalid input syntax for integer: "" CONTEXT: COPY , line 1, column : ""

代码看起来像这样:

table_data = StringIO.StringIO()
# Populate the table_data variable with rows delimited by \n and columns delimited by \t
cursor = db_connection.cursor()
cursor.copy_from(table_data, <table_name>)

此列是smallint列。

This column is a smallint column.

推荐答案

默认情况下, COPY FROM (和 copy_from )将NULL值编码为 \N 。如果您想使用空字符串表示NULL,则需要明确地这么说

By default, COPY FROM (and copy_from) encode a NULL value as \N. If you want to use the empty string to mean NULL, you need to say so explicitly:

cursor.copy_from(table_data, table_name, null="")

这篇关于用于加载数据的Python psycopg2 copy_from()会为空整数值引发错误:DataError:整数的无效输入语法:“”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆