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
    Commented 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
    Commented 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 ;) Commented 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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.