直接在Python中重新创建Postgres COPY? [英] Recreating Postgres COPY directly in Python?

查看:81
本文介绍了直接在Python中重新创建Postgres COPY?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据块,当前为n元组列表,但格式相当灵活,我想附加到Postgres表中-在这种情况下,每个n元组都对应于其中的一行

I have a block of data, currently as a list of n-tuples but the format is pretty flexible, that I'd like to append to a Postgres table - in this case, each n-tuple corresponds to a row in the DB.

到目前为止,我一直在做的工作是将所有内容写入CSV文件,然后使用postgres的COPY将所有内容批量加载到数据库中。这可行,但不是最佳选择,我希望能够直接从python进行所有操作。

What I had been doing up to this point is writing these all to a CSV file and then using postgres' COPY to bulk load all of this into the database. This works, but is suboptimal, I'd prefer to be able to do this all directly from python. Is there a method from within python to replicate the COPY type bulk load in Postgres?

推荐答案

如果您使用的是psycopg2驱动程序,是否可以使用python中的方法复制COPY类型的大容量负载? ,游标提供了 copy_to copy_from 函数,它们可以从任何类似文件的对象(包括 StringIO 缓冲区)。

If you're using the psycopg2 driver, the cursors provide a copy_to and copy_from function that can read from any file-like object (including a StringIO buffer).

文件 examples / copy_from.py psycopg2源分发附带的/copy_to.py rel = noreferrer>示例/copy_to.py

此摘录来自 copy_from.py 示例:

conn = psycopg2.connect(DSN)
curs = conn.cursor()
curs.execute("CREATE TABLE test_copy (fld1 text, fld2 text, fld3 int4)")

# anything can be used as a file if it has .read() and .readline() methods
data = StringIO.StringIO()
data.write('\n'.join(['Tom\tJenkins\t37',
                  'Madonna\t\N\t45',
                  'Federico\tDi Gregorio\t\N']))
data.seek(0)

curs.copy_from(data, 'test_copy')

这篇关于直接在Python中重新创建Postgres COPY?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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