用于加载数据的Python psycopg2 copy

编程入门 行业动态 更新时间:2024-10-27 14:30:32
本文介绍了用于加载数据的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

本文发布于:2023-05-26 19:28:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/265206.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:加载   数据   Python   copy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!