使用Python将CSV数据导入postgreSQL

2024-03-28 11:08:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用Python将CSV数据导入postgreSQL。当我运行代码时,它在(用户)附近显示一个错误。有人能提供帮助吗。我是编程新手,请原谅我的愚蠢。

import psycopg2
import csv

csv_data = csv.reader(file('SampleData2.csv'))

database = psycopg2.connect (database = "***", user="***", password="***", host="localhost", port="5432")

cursor = database.cursor()
delete = """Drop table if exists Real.SampleDataTwo"""
print (delete)

mydata = cursor.execute(delete)

cursor.execute("""Create Table Real.SampleDataTwo
                (User varchar(55),
                LastUpdate timestamp,
                Week date,
                Builder varchar(55),
                Traffic integer
                );""")

print "Table created successfully"

for row in csv_data:

    cursor.execute("INSERT INTO Real.SampleDataTwo (User, LastUpdate, Week, Builder, Traffic)"\
                "VALUES (%s,%s,%s,%s,%s)",
               row)


cursor.close()
database.commit()
database.close()

print "CSV data imported"

它显示的错误是:

Drop table if exists Real.SampleDataTwo

Traceback (most recent call last):
  File "C:/Users/Programming/Data.py", line 20, in <module>
);""")
ProgrammingError: syntax error at or near "User"
LINE 2:                 (User varchar(55),
                         ^

Tags: csvimportexecutedata错误deleterealcursor