【问题标题】:I am unable to COPY my CSV to postgres using psycopg2/copy_expert我无法使用 psycopg2/copy_expert 将我的 CSV 复制到 postgres
【发布时间】:2021-12-21 09:20:38
【问题描述】:

编辑: 在 postgresql.conf 中,log_statement 设置为: #log_statement = 'none' # none, ddl, mod, all

我的目标是将包含约 30 万条记录的 .cvs 文件复制到 Postgres。

我正在运行下面的脚本,但没有任何反应;没有错误或警告,但仍然没有上传 csv。

有什么想法吗?

import psycopg2

# Try to connect
try: 
  conn = psycopg2.connect(database="<db>", user="<user>", password="<pwd>", host="<host>", port="<port>")
  print("Database Connected....")
except:
  print("Unable to Connect....")


cur = conn.cursor()
try:    
  sqlstr = "COPY \"HISTORICALS\".\"HISTORICAL_DAILY_MASTER\" FROM STDIN DELIMITER ',' CSV"
  with open('/Users/kevin/Dropbox/Stonks/HISTORICALS/dump.csv') as f:
    cur.copy_expert(sqlstr, f)
  conn.commit()
  print("COPY pass")
except:
  print("Unable to COPY...")


# Close communication with the database
cur.close()
conn.close()

This is what my .csv looks like

谢谢!

凯文

【问题讨论】:

  • 执行此操作时 Postgres 日志会显示什么?添加信息以更新您的问题。也可以试试:open('/Users/kevin/Dropbox/Stonks/HISTORICALS/dump.csv', 'r')note 'r'。
  • @AdrianKlaver 谢谢,我添加了 'r' 和相同的结果。除了“无法复制...”之外,我没有其他日志
  • "Unable to COPY..." 是 Python 代码的输出。我所追求的是 Postgres 服务器日志中显示的内容。在postgresql.conf 中,log_statement 设置为什么?将此信息添加到您的问题中,而不是作为评论。
  • @AdrianKlaver,谢谢,信息已添加到问题中
  • 取消注释 log_statement 并设置为 log_statement = mod 然后 reload 服务器以捕捉更改。然后你应该在日志中看到当你执行COPY 时发生了什么。同样在exceptprint 异常:except psycopg2.Error as e: print(e)

标签: postgresql csv copy psycopg2


【解决方案1】:

我建议你第一次用 pandas 加载你的 df

import pandas as pd
import psycopg2
conn = psycopg2.connect(database="<db>", user="<user>", password="<pwd>", host="<host>", port="<port>")
cur = conn.cursor()
df = pd.read_csv('data.csv')
cur.copy_from(df, schema , null='', sep=',/;', columns=(df.columns))

对于部分 columns=(df.columns) 我忘记了他们是否想要 turple 或 list 但应该使用转换,你应该阅读这个 Pandas dataframe to PostgreSQL table using psycopg2 without SQLAlchemy?谁能帮到你

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-24
    • 2020-10-09
    • 2019-05-05
    • 2016-10-06
    • 2021-02-01
    • 2019-12-14
    相关资源
    最近更新 更多