48

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)
2
  • 5
    You must commit data, like conn.commit()
    – Denis
    Jan 31, 2012 at 6:53
  • For string interpolation you can now use: ('{0}', '{1}', '{2}') in place of (%s, %s, %s) above.
    – zero_cool
    Jan 17, 2017 at 3:38

1 Answer 1

56

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.

1
  • 1
    np, i make the same mistake all the time ;) Jan 31, 2012 at 6:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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