【问题标题】:importing CSV data into postgreSQL using Python使用 Python 将 CSV 数据导入 postgreSQL
【发布时间】:2017-03-11 19:16:04
【问题描述】:

我正在尝试使用 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),
                         ^

【问题讨论】:

  • 我认为你缺少 id 参数:id INT PRIMARY KEY NOT NULL,

标签: python postgresql csv


【解决方案1】:

尝试将用户更改为其他内容,看看问题是否已解决。如果没有,请尝试运行 PostgreSQL Python 指南给出的示例:http://www.postgresqltutorial.com/postgresql-python/create-tables/

【讨论】:

    【解决方案2】:

    【讨论】:

    • 谢谢 MKJ,你说得对。用户不能用作列名。
    猜你喜欢
    • 1970-01-01
    • 2022-01-21
    • 2021-10-12
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    • 2019-03-06
    • 1970-01-01
    相关资源
    最近更新 更多