gpt4 book ai didi

python - Psycopg2:cursor.execute 无法正常工作

转载 作者:行者123 更新时间:2023-11-28 20:18:26 26 4
gpt4 key购买 nike

因此,我有以下代码将旧数据库的数据插入到新数据库中:

...    
cur_old.execute("""SELECT DISTINCT module FROM all_students_users_log_course266""")
module_rows = cur_old.fetchall()

for row in module_rows:
cur_new.execute("""INSERT INTO modules(label) SELECT %s WHERE NOT EXISTS (SELECT 1 FROM modules WHERE label=%s)""", (row[0], row[0]))
...

最后一行执行一个查询,其中标签被插入到新的数据库表中。我在 pgAdmin 上测试了这个查询,它如我所愿地工作。

但是,当执行脚本时,modules 表中没有插入任何内容。 (实际上序列已更新,但表中未存储任何数据)。

从游标调用execute方法后还需要做其他事情吗?

(ps.脚本一直运行到最后没有报错)

最佳答案

您忘记执行 connection.commit()。数据库中的任何更改都必须在连接上进行提交。例如,sqlite3 documentation在第一个示例中清楚地说明了这一点:

# Save (commit) the changes.
conn.commit()

第一个例子在psycopg2 documentation做同样的事情:

# Make the changes to the database persistent
>>> conn.commit()

关于python - Psycopg2:cursor.execute 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36464592/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com