繁体   English   中英

使用Python将CSV数据导入PostgreSQL时出错

[英]Getting error in Importing CSV data into postgreSQL using Python

我正在尝试使用Python将我拥有的CSV数据导入到postgreSQL中。 运行代码时显示错误。

import csv
import psycopg2
import time
from datetime import datetime, timedelta

yesterday = datetime.strftime(datetime.now() - timedelta(1), '%Y%m%d')
print yesterday

conn = psycopg2.connect(host="172.19.1.228", database="stat", user="radio",
                        password="abcd1234", port="5432")

tem = "copy e_report FROM '/home/ftpuser/Report/Report_E_RadioStat_' & " \
      "'yesterday' & '.csv' With DELIMITER ',' CSV HEADER;"

cursor = conn.cursor()

cursor.execute(tem)

错误如下图所示:

Traceback (most recent call last):
  File "C:\Users\p4532\Desktop\python\python_test.py", line 22, in <module>
    cursor.execute(tem)
ProgrammingError: syntax error at or near "&"
LINE 1: ...t FROM '/home/ftpuser/Report/Report_E_RadioStat_' & 'yesterd...

请提出解决此错误的方法。

Postgresql中的文本串联运算符为||

'/home/ftpuser/Report/Report_E_RadioStat_' || 'yesterd...

https://www.postgresql.org/docs/current/static/functions-string.html#FUNCTIONS-STRING-SQL

请改用Psycopg copy_from

http://initd.org/psycopg/docs/cursor.html#cursor.copy_from

除了串联运算符之外,请注意,copy命令将文件名视为服务器上的路径。 如果要连接到远程数据库,则需要使用命令的from STDIN形式。 另外,由于文件中包含标头,因此应使用copy_expertcopy_from 后者也接受文件,但不允许您指定有标头。

sql = "copy e_report from stdin with delimiter ',' csv header"
with open(filename, 'r') as instream, conn.cursor() as cursor:
    cursor.copy_expert(sql, instream)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM