我一直在嘗試使用 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粉9905682832023-11-08 11:46:10
從 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}")