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

Python PostgreSQL代码遇TypeError参数转换错误,现有方案无效求助

解决方案

错误根源

  1. 参数格式错误:cursor.execute的第二个参数要求是序列(元组/列表),但(headline)不是元组——Python中单个元素的元组必须在末尾加逗号((headline,)),否则会被解析成字符串本身,导致psycopg2无法匹配SQL占位符。
  2. SQL占位符用法不当:单条插入的SQL应该用(%s)作为占位符,你写的VALUES %s是批量插入的格式,需要配合execute_values使用,单条插入不需要这样写。

修复代码

修改database.py中的两处关键地方

# 1. 修正单条插入的SQL语句
INSERT_HEADLINE = "INSERT INTO headlines (headline) VALUES (%s);"

# 2. 修正add_headline函数的参数传递
def add_headline(connection, headline):
    with connection:
        with connection.cursor() as cursor:
            # 末尾加逗号,确保是元组类型
            cursor.execute(INSERT_HEADLINE, (headline,))        

额外优化

  • 删除重复的create_headlines函数,它和create_tables功能完全一致,保留一个即可。
  • 如果后续需要批量插入多条数据,再使用execute_values,示例代码:
# 批量插入的SQL
INSERT_HEADLINE_BATCH = "INSERT INTO headlines (headline) VALUES %s;"

def add_headlines_batch(connection, headlines_list):
    with connection:
        with connection.cursor() as cursor:
            # 把每个headline包装成元组,再传入execute_values
            execute_values(cursor, INSERT_HEADLINE_BATCH, [(h,) for h in headlines_list])

验证修复

修改后重新运行app.py,即可成功插入数据。你可以在代码末尾添加以下代码验证结果:

print(database.get_headlines(connection))

内容的提问来源于stack exchange,提问作者jdm79

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 20:20:04