postgresql 使用 psycopg2 库复制命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17559300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 01:00:34  来源:igfitidea点击:

copy command with psycopg2 library

pythonpostgresqlpsycopg2

提问by user680839

Is it possible to run the command below through psycopg2? If so, how can I do it?

是否可以通过 psycopg2 运行以下命令?如果是这样,我该怎么做?

COPY table_name(col1,col2) FROM 'path/to/file.csv' WITH HEADER DELIMITER ',' CSV;

回答by Sean

Yes!

是的!

You can use the copy_frommethod:

您可以使用以下copy_from方法

import psycopg2
dbname=...
user=...
password=...
host=...
port=...
con = psycopg2.connect(database=dbname,user=user,password=password,host=host,port=port)
cur = con.cursor()    
f = open('path/to/file.csv')
cur.copy_from(f, 'test', columns=('col1', 'col2'), sep=",")
con.commit()
con.close()

回答by Craig Ringer

A Google search for psycopg2 copyfinds, as the first hit for me, the psycopg manual, which includes instructions on using client-side COPY.

谷歌搜索psycopg2 copy找到了 psycopg 手册,作为我的第一个搜索结果,其中包含有关使用客户端COPY.

If you want server-side COPYyou just run the statement like any other SQL.

如果您想要服务器端,COPY您只需像任何其他 SQL 一样运行该语句。

As written above the command doesn't make any sense. I presume you meant to write a COPY ... TOor COPY ... FROMcommand and mangled it while hiding the real file name, etc.

如上所述,该命令没有任何意义。我认为您打算编写一个COPY ... TOorCOPY ... FROM命令并在隐藏真实文件名等的同时对其进行修改。