sqlalchemy.exc.ArgumentError: 列表參數必須只包含元組或字典
P粉080643975
P粉080643975 2023-11-07 21:06:02
0
1
888

我一直在嘗試使用 sqlalchemy 將資料轉儲到 mysql 資料庫中。當我嘗試這樣做時,它給出錯誤 sqlalchemy.exc.ArgumentError:列表參數必須只包含元組或字典 。以下代碼用於插入。

def insert_data(db, table, rows):

    db.execute(f"INSERT INTO {table} VALUES (%s)", rows)
    db.commit()

rows中的內容如下。

[(1, 'asdsewadada', 'lajsdljasld', 'lol@gmail.com', 51)]

所以,我插入的是元組列表,但仍然遇到相同的錯誤。

P粉080643975
P粉080643975

全部回覆(1)
P粉990568283

從 SQLAlchemy 版本 2 開始,您應該使用字典而不是元組:

所以這應該會修復你的程式碼:

def insert_data(db: sqlalchemy.engine.base.Engine, query: str, parameters: dict):
    log_headline: str = "insert_data() ::"
    """
    :param db:
    :param query: INSERT INTO votes (time_cast, candidate) VALUES (:time_cast, :candidate)
    :param parameters: {"time_cast": time_cast, "candidate": team}
    :return:
    """

    # Insert
    stmt = sqlalchemy.text(query)
    try:
        # Using a with statement ensures that the connection is always released
        # back into the pool at the end of statement (even if an error occurs)
        with db.connect() as conn:
            conn.execute(stmt, parameters=parameters)
            conn.commit()
        print(f"{log_headline} OK inserted data ")
    except Exception as e:
        # If something goes wrong, handle the error in this section. This might
        # involve retrying or adjusting parameters depending on the situation.
        print(f"{log_headline} Error {e}")
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!