Using INSERT with a PostgreSQL Database using Python

Question:

I am trying to insert data into a PostgreSQL database table using Python. I don’t see any syntax errors but, for some reason, my data isn’t getting inserted into the database.

conn = psycopg2.connect(connection)
cursor = conn.cursor()
items = pickle.load(open(pickle_file,"rb"))

for item in items:
    city = item[0]
    price = item[1]
    info = item[2]

    query =  "INSERT INTO items (info, city, price) VALUES (%s, %s, %s);"
    data = (info, city, price)

    cursor.execute(query, data)
Asked By: Ching Chong

||

Answers:

You have to commit the transaction.

conn.commit()

If there’s no reason to think the transaction will fail, it’s faster to commit after the for loop finishes.

Answered By: GuillaumeDufay
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.