【问题标题】:Copying from a CSV to Postgres database on Heroku在 Heroku 上从 CSV 复制到 Postgres 数据库
【发布时间】:2015-04-21 00:12:00
【问题描述】:

我正在尝试使用在 Heroku 应用程序上运行的 python 脚本将数据从 CSV 文件复制到 Postgres 数据库(该数据库附加到所述 Heroku 应用程序)。我遇到的问题是 Heroku 不允许超级用户访问 Postgres,因此我的脚本无法运行 COPY FROM 'filename' Postgres 命令。我尝试使用 COPY FROM STDIN 代替,但无济于事。

下面的代码有问题吗?或者也许我可以通过另一种方式在我的脚本中实现从 CSV 文件复制到我的 Heroku Postgres 数据库的任务?在终端中手动运行 psql 命令不是一种选择,因为重点是自动化复制过程以使我的数据库保持最新,而无需我触摸它。

#copysql is a string with the command for copying from the CSV file; newvals is the name of a temporary table I will use for the data imported from the CSV file
copysql = """COPY newvals FROM STDIN (FORMAT csv, NULL 'NULL');"""
#sqlquery is the SQL string for inserting new data found in the temporary table which is created from the CSV import into the existing Postgres database
sqlquery = """INSERT INTO desttable SELECT newvals.id, newvals.column1, newvals.column2 FROM newvals LEFT OUTER JOIN desttable ON (desttable.id = newvals.id) WHERE desttable.id IS NULL;"""

#my CSV file is called 'csvfile' and cur is the database cursor (using psycopg2 and I have already connected to the db elsewhere in my script)
cur.execute("DROP TABLE IF EXISTS newvals;")
cur.execute("CREATE TEMPORARY TABLE newvals AS SELECT * FROM desttable LIMIT 0;")
cur.copy_expert(sql=copysql,file=csvfile)
cur.execute(sqlquery)

【问题讨论】:

  • 您总是可以解析文件并运行插入语句。它会很慢,但如果性能不是关键的话......
  • @Nick 这是我决定采用的方法并且它有效,但我担心随着数据库变大而导致性能下降

标签: python csv heroku-postgres


【解决方案1】:

只需从 Heroku Web 界面获取 SQL URL (postgres://...)。然后您可以在本地运行脚本并连接到 Heroku Postgres。这就是我解决问题的方法。

【讨论】:

  • 如果您仍在使用 Heroku Postgres,在本地运行脚本是否会绕过权限问题?另外,您是通过 cron 之类的调度程序还是其他方式自动运行脚本?
猜你喜欢
  • 1970-01-01
  • 2012-04-27
  • 2014-05-30
  • 2011-11-29
  • 2018-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-17
相关资源
最近更新 更多