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() Commented Jan 31, 2012 at 6:53
  • For string interpolation you can now use: ('{0}', '{1}', '{2}') in place of (%s, %s, %s) above. 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.

Sign up to request clarification or add additional context in comments.

1 Comment

np, i make the same mistake all the time ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.