Psycopg2:cursor.execute无法正常工作

Joa*_*des 2 python postgresql psycopg2

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

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

最后一行执行查询,其中标签插入到新数据库表中.我测试了这个查询pgAdmin,它可以按我的意愿运行.

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

从光标调用execute方法后,是否还需要执行其他操作?

(Ps.脚本运行到最后没有任何错误)

小智 7

你忘了做connection.commit().数据库中的任何更改都必须在连接上提交.例如,sqlite3文档在第一个示例中清楚地说明了它:

# Save (commit) the changes.
conn.commit()
Run Code Online (Sandbox Code Playgroud)

psycopg2文档中的第一个示例也是如此:

# Make the changes to the database persistent
>>> conn.commit()
Run Code Online (Sandbox Code Playgroud)