python-如何在SQLAlchemy Core中将列名作为参数传递?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python-如何在SQLAlchemy Core中将列名作为参数传递?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2615字,纯文字阅读大概需要4分钟。
内容图文
我有一个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()
解决方法:
我不确定我是否了解您想要的内容,并且您的代码看起来与我认为的惯用sqlalchemy完全不同(我没有批评,只是在评论我们可能使用正交代码样式).
如果要传递文字列作为参数,请使用:
from sqlalchemy.sql import literal_column
...
tbl.update().where(
tbl.c.id == bindparam('b_id')
).values(
tbl.c.column_to_update == literal_column('b_column_to_update')
)
如果要动态设置表达式的右侧,请使用:
tbl.update().where(
tbl.c.id == bindparam('b_id')
).values(
getattr(tbl.c, 'column_to_update') == bindparam('b_column_to_update')
)
如果这些都不是您想要的,请评论答案或改善您的问题,我将尽力提供帮助.
[更新]
values方法使用诸如.values(column_to_update = value)之类的命名参数,其中column_to_update是实际的列名,而不是保存列名的变量.例:
stmt = users.update(). where(users.c.id==5). values(id=-5)
请注意,其中使用比较运算符==,而值使用归因运算符= -前者使用布尔表达式中的列对象,后者使用列名作为关键字参数绑定.
如果您希望它是动态的,请使用** kwargs表示法:.values(** {‘column_to_update’:value})
但是可能您想使用values参数而不是values方法.
内容总结
以上是互联网集市为您收集整理的python-如何在SQLAlchemy Core中将列名作为参数传递?全部内容,希望文章能够帮你解决python-如何在SQLAlchemy Core中将列名作为参数传递?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。