2017-02-20 115 views
0

我正在尝试导入使用Python导入到PostgreSQL中的CSV数据。它显示一个错误,当我运行代码。使用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... 

请提出一个方法来解决此问题。

回答

0

除了连接操作,注意复制命令将文件名视为路径在服务器上。如果要连接到远程数据库,则需要使用命令的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) 
相关问题