简体   繁体   中英

Using INSERT with a PostgreSQL Database using Python

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM