python传递参数给sql_python-如何在SQLAlchemy Core中将列名作为参数传递?

我有一个sqlalchemy核心批量更新查询,我需要以编程方式传递要更新的列的名称.

该函数如下所示,其中包含每个变量的注释:

def update_columns(table_name, pids, column_to_update):

'''

1. table_name: a string denoting the name of the table to be updated

2. pid: a list of primary ids

3. column_to_update: a string representing the name of the column that will be flagged. Sometimes the name can be is_processed or is_active and several more other columns. I thus need to pass the name as a parameter.

'''

for pid in pids:

COL_DICT_UPDATE = {}

COL_DICT_UPDATE['b_id'] = pid

COL_DICT_UPDATE['b_column_to_update'] = True

COL_LIST_UPDATE.append(COL_DICT_UPDATE)

tbl = Table(table_name, meta, autoload=True, autoload_with=Engine)

trans = CONN.begin()

stmt = tbl.update().where(tbl.c.id == bindparam('b_id')).values(tbl.c.column_to_update==bindparam('b_column_to_update'))

trans.commit()

table参数被接受并且可以正常工作.

作为参数传递时,column_to_update不起作用.它失败,并出现错误引发AttributeError(key)AttributeError:column_to_mark.但是,如果我对列名进行了硬编码,则查询将运行.

如何传递column_to_update的名称以供SQLAlchemy识别?

编辑:最终脚本

感谢@Paulo,最终脚本如下所示:

def update_columns(table_name, pids, column_to_update):

for pid in pids:

COL_DICT_UPDATE = {}

COL_DICT_UPDATE['b_id'] = pid

COL_DICT_UPDATE['b_column_to_update'] = True

COL_LIST_UPDATE.append(COL_DICT_UPDATE)

tbl = Table(table_name, meta, autoload=True, autoload_with=Engine)

trans = CONN.begin()

stmt = tbl.update().where(

tbl.c.id == bindparam('b_id')

).values(**{column_to_update: bindparam('b_column_to_update')})

CONN.execute(stmt, COL_LIST_UPDATE)

trans.commit()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值