日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

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

發布時間:2023/12/19 python 43 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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()

總結

以上是生活随笔為你收集整理的python传递参数给sql_python-如何在SQLAlchemy Core中将列名作为参数传递?的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。