sqlalchemy.exc.ArgumentError: 列表参数必须仅包含元组或字典
P粉080643975
P粉080643975 2023-11-07 21:06:02
0
1
1012

我一直在尝试使用 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}")
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板