使用Python将INSERT与PostgreSQL数据库一起使用

Chi*_*ong 36 python postgresql psycopg2

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

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)
Run Code Online (Sandbox Code Playgroud)

Gui*_*fay 44

您必须提交交易.

conn.commit()
Run Code Online (Sandbox Code Playgroud)

如果没有理由认为事务会失败,那么在for循环结束后提交会更快.