search

Home  >  Q&A  >  body text

sqlalchemy.exc.ArgumentError: list argument must contain only tuples or dictionaries

I've been trying to use sqlalchemy to dump data into a mysql database. When I try to do this, it gives the error sqlalchemy.exc.ArgumentError: List arguments must contain only tuples or dictionaries . The following code is used for insertion.

def insert_data(db, table, rows):

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

rows is as follows.

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

So, I'm inserting a list of tuples, but still getting the same error.

P粉080643975P粉080643975381 days ago1018

reply all(1)I'll reply

  • P粉990568283

    P粉9905682832023-11-08 11:46:10

    Starting with SQLAlchemy version 2, you should use dictionaries instead of tuples:

    So this should fix your code:

    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}")

    reply
    0
  • Cancelreply