簡體   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