Search code examples
pythonsqlalchemy

how to set autocommit = 1 in a sqlalchemy.engine.Connection


In sqlalchemy, I make the connection:

 conn = engine.connect()

I found this will set autocommit = 0 in my mysqld log. Now I want to set autocommit = 1 because I do not want to query in a transaction.

Is there a way to do this?


Solution

  • From The SQLAlchemy documentation: Understanding autocommit

    conn = engine.connect()
    conn.execute("INSERT INTO users VALUES (1, 'john')")  # autocommits
    

    The “autocommit” feature is only in effect when no Transaction has otherwise been declared. This means the feature is not generally used with the ORM, as the Session object by default always maintains an ongoing Transaction.

    Full control of the “autocommit” behavior is available using the generative Connection.execution_options() method provided on Connection, Engine, Executable, using the “autocommit” flag which will turn on or off the autocommit for the selected scope. For example, a text() construct representing a stored procedure that commits might use it so that a SELECT statement will issue a COMMIT:

    engine.execute(text("SELECT my_mutating_procedure()").execution_options(autocommit=True))