python - 在 Python 中使用 Postgres 的 COPY FROM 文件查询而不写入临时文件

标签 python postgresql csv postgresql-copy

我需要将数据从一些源数据源加载到 Postgres 数据库。 为完成此任务,我首先将数据写入临时 CSV 文件,然后使用 COPY FROM 查询将数据从 CSV 文件加载到 Postgres 数据库。我在 Python 上完成所有这些。

代码如下所示:

table_name = 'products'
temp_file = "'C:\\Users\\username\\tempfile.csv'"
db_conn = psycopg2.connect(host, port, user, password, database)
cursor = db_conn.cursor()
query = """COPY """ + table_name + """ FROM """ + temp_file + " WITH NULL AS ''; """
cursor.execute(query)

我想避免写入中间文件的步骤。相反,我想写入一个 Python 对象,然后使用 COPY FROM 文件方法将数据加载到 postgres 数据库。

我知道 this technique of using psycopg2's copy_from method which copies data from a StringIO object to the postgres database .但是,由于某种原因我不能使用 psycopg2,因此我不希望我的 COPY FROM 任务依赖于库。我希望它是 Postgres 查询,它也可以由任何其他 postgres 驱动程序运行。

请提出一种无需写入中间文件即可执行此操作的更好方法。

最佳答案

您可以从脚本中调用 psql 命令行工具(即使用 subprocess.call)并利用其 \copy 命令,将一个实例的输出通过管道传输到另一个实例的输入,避免使用临时文件。即

psql -X -h from_host -U user -c "\copy from_table to stdout"| psql -X -h to_host -U user -c "\copy to_table from stdin"

这假定该表存在于目标数据库中。如果没有,首先需要一个单独的命令来创建它。

另请注意,此方法的一个警告是来自第一个 psql 调用的错误可能会被管道进程吞没。

关于python - 在 Python 中使用 Postgres 的 COPY FROM 文件查询而不写入临时文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26722940/

相关文章:

python - Django 应用程序中的 AJAX 上传问题

python - 类型错误 : argument 1 must have a "write" method

postgresql - CentOS 上的 PostgreSQL 和 ESRI Geoportal 安装问题

python - 值错误 : Cannot cast DatetimeIndex to dtype datetime64[us]

java.sql.SQLException : Row 1 was truncated; it contained more data than there were input columns 异常

java - 从不同 Tomcat 上的 Tomcat webapps 读取文件

线程 "main"java.lang.NegativeArraySizeException : -28 中的 Java ArrayList 异常

python - 如何用pytest编写正确的测试?

django - 函数内的 Postgres 咨询锁允许并发执行

python - 在Python中,检索Xml属性值