10

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?

1
  • 2
    You are linking to the documentation of a SQLAlchemy version that is different from what you are using. Commented Nov 18, 2022 at 21:56

2 Answers 2

20

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():

Sign up to request clarification or add additional context in comments.

Comments

5

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.