I am trying to import CSV data I have into postgreSQL using Python. It shows an error near (User) when I run the code. Can someone please provide assistance. I am new to Programming so please pardon my stupidity.

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"

The error it shows is:

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),
                         ^
share|improve this question
2  
I think you're missing id param: id INT PRIMARY KEY NOT NULL, – Jean-François Fabre Oct 28 '16 at 20:36
up vote 4 down vote accepted

I believe user is not allowed as column name. See https://www.postgresql.org/docs/current/static/sql-keywords-appendix.html#KEYWORDS-TABLE

share|improve this answer
3  
Thanks MKJ, you're absolutely right. User can't be used as column name. – Jacob_Cortese Oct 28 '16 at 20:56

Try change User to something else and see if the issue is fixed. If not, then try to run the example given by PostgreSQL Python guide: http://www.postgresqltutorial.com/postgresql-python/create-tables/

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.