Python 从CSV复制到Heroku上的Postgres数据库

Python 从CSV复制到Heroku上的Postgres数据库,python,csv,heroku-postgres,Python,Csv,Heroku Postgres,我正在尝试使用Heroku应用程序上运行的python脚本将CSV文件中的数据复制到Postgres数据库,该数据库连接到Heroku应用程序。我遇到的问题是Heroku不允许超级用户访问Postgres,因此我的脚本无法运行“从文件名”Postgres复制命令。我试过用STDIN的COPY代替,但没有用 下面的代码有问题吗?或者,我可以用另一种方式在脚本中实现从CSV文件复制到Heroku Postgres数据库的任务?在终端中手动运行psql命令不是一个选项,因为整个要点是自动化复制过程,使

我正在尝试使用Heroku应用程序上运行的python脚本将CSV文件中的数据复制到Postgres数据库,该数据库连接到Heroku应用程序。我遇到的问题是Heroku不允许超级用户访问Postgres,因此我的脚本无法运行“从文件名”Postgres复制命令。我试过用STDIN的COPY代替,但没有用

下面的代码有问题吗?或者,我可以用另一种方式在脚本中实现从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)

只需获取SQL URL即可postgres://... 退出Heroku web界面。然后您可以在本地运行脚本并连接到Heroku Postgres。这就是我为我的案例解决问题的方法。

您始终可以解析文件并运行insert语句。这会很慢,但如果性能不是关键…@Nick这是我决定采用的方法,它是有效的,但我担心随着db的增长,性能会越来越高。如果您仍然使用Heroku Postgres,在本地运行脚本会绕过权限问题吗?另外,您是否通过cron之类的调度器或其他方式自动运行脚本?