You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用预准备语句执行Python脚本无报错但未插入PostgreSQL数据

问题分析与解决方案:PostgreSQL插入数据无报错但无数据

核心原因:事务未提交

psycopg2默认开启事务模式,执行INSERT等写操作后,必须手动提交事务,否则所有操作会在连接关闭时自动回滚,导致数据库中无数据。你的代码完全缺失了提交步骤。

其他潜在排查点

  1. 正则匹配是否生效:如果list_of_strings为空,说明没从文件中提取到数据,需检查file.txt的格式是否符合“名言内容” (作者)的结构。
  2. 冗余连接资源:代码开头的全局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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 12:35:14