Python psycopg2 copy_from()加载数据会抛出空整数值的错误:DataError:整数的输入语法无效:""

use*_*637 4 python postgresql psycopg2

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

我的copy_from在第一个记录本身失败,特别是对于具有空值(''没有引号)的特定(可空)整数列.我也尝试使用Python的None关键字而不是''用于NULL值.它抛出以下错误: DataError:整数的输入语法无效:""语境:COPY,第1行,列:""

代码看起来像这样:

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>)
Run Code Online (Sandbox Code Playgroud)

此列是smallint列.

Eev*_*vee 9

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

cursor.copy_from(table_data, table_name, null="")
Run Code Online (Sandbox Code Playgroud)