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

如何在Python中将字符串参数传入DB2的SQL查询并解决ibm_db执行报错

问题原因

你报错的核心是混淆了ibm_db模块两个执行方法的使用场景:

  • ibm_db.exec_immediate() 要求第二个参数是原始SQL字符串,仅适合无参数、单次执行的SQL
  • 你已经通过ibm_db.prepare()生成了预编译语句对象,绑定参数后应该调用ibm_db.execute()执行预编译对象,不能再传给exec_immediate

还有两个容易触发报错的细节问题:

  • Python类型标注里字符串类型是str,不是string
  • while循环条件后面缺少冒号,会触发语法错误

修正后的完整代码

import ibm_db
# 连接初始化逻辑保持不变
conn_str = 'database=xxx;hostname=x.x.x.x;port=xxxx;protocol=TCPIP;UID=xxxxx;pwd=secret;'
ibm_db_conn = ibm_db.connect(conn_str,'','')

def question_to_db(tel : str):
    sql = "SELECT * from mper where mper.tel = ?"
    # 预编译带参数的SQL
    prepared_stmt = ibm_db.prepare(ibm_db_conn, sql)
    # 绑定参数
    ibm_db.bind_param(prepared_stmt, 1, tel, ibm_db.SQL_PARAM_INPUT, ibm_db.SQLCHAR)
    # 执行预编译语句,返回执行状态
    execute_success = ibm_db.execute(prepared_stmt)
    
    if execute_success:
        # 逐行读取结果
        row = ibm_db.fetch_both(prepared_stmt)
        while row != False:
            # 替换为你自己的行处理逻辑
            do_smth_with_row(row)
            row = ibm_db.fetch_both(prepared_stmt)
    return True

简化写法

可以省去单独调用bind_param的步骤,直接在执行时传入参数列表:

def question_to_db(tel : str):
    sql = "SELECT * from mper where mper.tel = ?"
    prepared_stmt = ibm_db.prepare(ibm_db_conn, sql)
    # 直接把参数封装成元组传给execute即可
    if ibm_db.execute(prepared_stmt, (tel,)):
        row = ibm_db.fetch_both(prepared_stmt)
        while row:
            do_smth_with_row(row)
            row = ibm_db.fetch_both(prepared_stmt)
    return True

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 08:15:02