使用预准备语句执行Python脚本无报错但未插入PostgreSQL数据
问题分析与解决方案:PostgreSQL插入数据无报错但无数据
核心原因:事务未提交
psycopg2默认开启事务模式,执行INSERT等写操作后,必须手动提交事务,否则所有操作会在连接关闭时自动回滚,导致数据库中无数据。你的代码完全缺失了提交步骤。
其他潜在排查点
- 正则匹配是否生效:如果
list_of_strings为空,说明没从文件中提取到数据,需检查file.txt的格式是否符合“名言内容” (作者)的结构。 - 冗余连接资源:代码开头的全局
conn变量未被使用,属于无效连接,应移除避免资源浪费。
修改后的代码
#!/usr/bin/python import psycopg2 import re from config import config data = None with open('file.txt', 'r') as file: data = file.read() list_of_strings = re.findall('“(.+?)” \(.+?\)', data, re.DOTALL) # 验证是否提取到数据 print(f"匹配到{len(list_of_strings)}条名言") def insert_quotes(): """ Connect to the PostgreSQL database server """ conn = None try: params = config() print('Connecting to the PostgreSQL database...') conn = psycopg2.connect(**params) cur = conn.cursor() # 替换变量名,避免覆盖内置str类型 for quote_str in list_of_strings: cur.execute("INSERT INTO the_courage_to_be_disliked (quote) VALUES (%s)", (quote_str,)) # 关键:提交事务 conn.commit() print(f"成功插入{len(list_of_strings)}条数据") cur.close() except (Exception, psycopg2.DatabaseError) as error: print(error) # 出错时回滚事务,避免事务挂起 if conn is not None: conn.rollback() finally: if conn is not None: conn.close() print('Database connection closed.') if __name__ == '__main__': insert_quotes()
关键修改说明
- 添加
conn.commit():确保插入操作被持久化到数据库 - 增加匹配数量打印:快速排查是否是数据提取环节的问题
- 优化变量名:避免使用
str作为变量名覆盖内置类型 - 增加异常回滚:出错时及时回滚事务,防止数据库资源占用
内容的提问来源于stack exchange,提问作者gtrman97
相关产品推荐
相关产品推荐

