我正在尝试使用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
发布评论