python传递参数给sql_python-如何在SQLAlchemy Core中将列名作为参数传递?
我有一個sqlalchemy核心批量更新查詢,我需要以編程方式傳遞要更新的列的名稱.
該函數(shù)如下所示,其中包含每個變量的注釋:
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參數(shù)被接受并且可以正常工作.
作為參數(shù)傳遞時,column_to_update不起作用.它失敗,并出現(xiàn)錯誤引發(fā)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()
總結(jié)
以上是生活随笔為你收集整理的python传递参数给sql_python-如何在SQLAlchemy Core中将列名作为参数传递?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 告诉你银行在年底为存储做的小动作
- 下一篇: OpenDDS用idl生成自定义数据类型