使用Python将INSERT与PostgreSQL数据库结合使用 [英] Using INSERT with a PostgreSQL Database using Python

查看:684
本文介绍了使用Python将INSERT与PostgreSQL数据库结合使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Python将数据插入PostgreSQL数据库表中。我没有看到任何语法错误,但是由于某种原因,我的数据没有插入数据库中。

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)


推荐答案

您必须提交事务。

conn.commit()

如果没有理由认为交易会失败,则在提交之后提交的速度更快循环结束。

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

这篇关于使用Python将INSERT与PostgreSQL数据库结合使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆