You need to enable JavaScript to run this app. Flask操作PostgreSQL执行SQL时出现多类TypeError问题求助
优惠活动
大模型
产品
解决方案
定价
更多

Flask操作PostgreSQL执行SQL时出现多类TypeError问题求助

报错触发原因
  • 第一个报错 TypeError: argument 1 must be a string or unicode object: got list instead:你将SQL语句和参数共同包裹在列表[]中赋值给了postgreSQL_select_Query_2,但PostgreSQL驱动(psycopg2)的cursor.execute方法第一个入参要求是纯SQL字符串,不能传入列表类型。
  • 第二个报错 TypeError: unhashable type: 'dict':你后续测试时错误将SQL语句和参数字典放在大括号{}中,这会被Python识别为集合类型,而字典属于不可哈希类型,不能作为集合的元素存入,因此触发报错。
  • 第三个报错 TypeError: list indices must be integers or slices, not str:是你之前错误把存储了SQL和参数的列表当成字典,用字符串键取值导致的类型错误。
  • 额外逻辑问题:你调用cursor.execute时的传参逻辑完全错误,如果你使用%(key)s格式的命名参数占位符,第二个参数需要直接传入参数对应的字典,不需要单独传postcodevar变量。
修复后的代码

按照PostgreSQL驱动要求拆分SQL字符串和参数即可,修复后代码如下:

def search(gss=None, description=None, postcode=None):
    if request.method == "POST":
        postcodevar = request.form['postcodevar']

        print("Assigning SQL statement to a postgreSQL variable")
        # 单独定义SQL字符串,不要包裹在列表/集合中
        postgreSQL_select_Query_2 = """SELECT DISTINCT gss,description,
        postcode FROM postcodelatlng pt, gss.shapes g 
        WHERE st_contains(geom,pos) AND %(postcode)s~* '(\y(?:[A-PR-    
        UWYZ](?:[A-HK-]?\d{1,2}|d[A-HJKMNP-Y]|[A-HK-Y]\d[ABEHMNPRV-
        Y]))(?:\s*\d[ABD-HJLNP-UW-]{2})\y)' 
        LIMIT 50"""
        # 单独定义参数字典
        query_params = {'postcode': postcodevar}

        # 按驱动要求传参:第一个参数是SQL字符串,第二个是参数字典
        cursor.execute(postgreSQL_select_Query_2, query_params)
        print("Selecting rows from mobile table using cursor.fetchall")
        records = cursor.fetchall()
        return render_template('idm_prototype.html', data=records)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 13:12:01