Brian Risk
Brian Risk

Reputation: 1449

SQLAlchemy: AttributeError: 'Connection' object has no attribute 'commit'

When using SQLAlchemy (version 1.4.44) to create, drop or otherwise modify tables, the updates don't appear to be committing. Attempting to solve this, I'm following the docs and using the commit() function. Here's a simple example

from sqlalchemy import create_engine, text

engine = create_engine("postgresql://user:password@connection_string:5432/database_name")
with engine.connect() as connection:
    sql = "create table test as (select count(1) as result from userquery);"
    result = connection.execute(text(sql))
    connection.commit()

This produces the error:

AttributeError: 'Connection' object has no attribute 'commit'

What am I missing?

Upvotes: 10

Views: 17950

Answers (2)

Andrew Demidov
Andrew Demidov

Reputation: 51

The documentation is actually misleading (version 1.4). We can see using Connection.commit() method in documentation describing rows inserting, but the method doesn't exist. I have managed to find a clarity explanation for using transations in the transactions section:

The block managed by each .begin() method has the behavior such that the transaction is committed when the block completes. If an exception is raised, the transaction is instead rolled back, and the exception propagated outwards.

Example from documentation below. There is no commit() method calling.

    # runs a transaction
    with engine.begin() as connection:
        r1 = connection.execute(table1.select())
        connection.execute(table1.insert(), {"col1": 7, "col2": "this is some data"})

Upvotes: 5

Ian Wilson
Ian Wilson

Reputation: 9119

The comment on the question is correct you are looking at the 2.0 docs but all you need to do is set future=True when calling create_engine() to use the "commit as you go" functionality provided in 2.0.

SEE migration-core-connection-transaction

When using 2.0 style with the create_engine.future flag, “commit as you go” style may also be used, as the Connection features autobegin behavior, which takes place when a statement is first invoked in the absence of an explicit call to Connection.begin():

Upvotes: 20

Related Questions