There was a change from 1.4 to 2.0. The above code will run fine with sqlalchemy version 1.4 I believe. setting SQLALCHEMY_WARN_20=1 python and running the above code reveals this warning:

<stdin>:1: RemovedIn20Warning: The Engine.execute() method is considered legacy as of the 1.x series of SQLAlchemy and will be removed in 2.0. All statement execution in SQLAlchemy 2.0 is performed by the Connection.execute() method of Connection, or in the ORM by the Session.execute() method of Session. (Background on SQLAlchemy 2.0 at: https://sqlalche.me/e/b8d9)

So the correct way to do the code now is:

with engine.connect() as conn:
    result = conn.execute(stmt)

source here describing the behavior in 1.4 and here describing the behavior in 2.0

Answer from jonathan-dufault-kr on Stack Overflow
Top answer
1 of 3
55

There was a change from 1.4 to 2.0. The above code will run fine with sqlalchemy version 1.4 I believe. setting SQLALCHEMY_WARN_20=1 python and running the above code reveals this warning:

<stdin>:1: RemovedIn20Warning: The Engine.execute() method is considered legacy as of the 1.x series of SQLAlchemy and will be removed in 2.0. All statement execution in SQLAlchemy 2.0 is performed by the Connection.execute() method of Connection, or in the ORM by the Session.execute() method of Session. (Background on SQLAlchemy 2.0 at: https://sqlalche.me/e/b8d9)

So the correct way to do the code now is:

with engine.connect() as conn:
    result = conn.execute(stmt)

source here describing the behavior in 1.4 and here describing the behavior in 2.0

2 of 3
15
sql = f"""INSERT INTO user_apis
  (api_id, user_id, monthly_requests, total_requests)
  VALUES (1, {current_user.id}, 0, 0)"""

1.x

result = db.engine.execute(sql)

2.x

from sqlalchemy import text
with db.engine.begin() as conn:
    result = conn.execute(text(sql)) 
    conn.commit()              #2.x execute now only works with SELECT.
                               #Inserts, Updates and Deletes now must be 
                               #in a transaction and explicitly committed
                               #use engine echo=True to show transaction status

SELECT sql

with db.engine.connect() as conn:
    result = conn.execute(text(sql)).fetchall()

Add this method to do the right thing on both versions.

Then change all your db.engine.execute(sql) to myengine_execute(sql)

def myengine_execute(sql): 
  #If sqlalchemy version starts with 1.4 then do it the old way
  sqlalchemy_version = version("sqlalchemy")
  if sqlalchemy_version.startswith('1.4.'):
    with engine.connect() as conn: 
        return conn.execute(text(sql)) 
  else:
    #otherwise do it the new way with transactions:
    with engine.connect() as conn: 
        result = conn.execute(text(sql)) 
        #print(result.inserted_primary_key()) 
        conn.commit()

upd_sql = "update bankaccount set amount = amount+5e10 where id = 1234567" 
result = myengine_execute(upd_sql) 
Discussions

Unable to Validate Expectation Suit with PostgresSQL (No execute Attribute for Engine Object)
Good Day GEX Community, We have been testing Great Expectation for PostgresSQL for our organisation. We are successfully able to creating data source and expectation suit but upon performing the validation, we are facing the issue of not having execute attribute for the Engine object ... More on discourse.greatexpectations.io
🌐 discourse.greatexpectations.io
0
0
February 9, 2023
AttributeError: 'Engine' object has no attribute 'character_set_name'
I am running a python app on GCP app engine which connects to cloud SQL database (mySQL). But there is an error in GCP logs that I am unable to resolve, File “/layers/google.python.pip/pip/lib/python3.9/site-packages/sqlalchemy/dialects/mysql/mysqldb.py”, line 161, in on_connect charset_name ... More on discuss.google.dev
🌐 discuss.google.dev
0
0
December 22, 2023
Sqlite error
You need to share your code or no one can really help. More on reddit.com
🌐 r/learnpython
4
1
January 31, 2023
I keep getting this message ('NoneType' object has no attribute 'cursor') on one of my old projects any thoughts?

You have got an error because the getDbConnection function failed to connect to the database and hence returned None. Apart from this the whole structure of this program looks wrong. Why are you calling `getDbConnection` inside closeDbConnection ? You don't need to execute USE Enrolment everytime. You can refer to a table using Enrolment.<Table_name>. Refer to https://flask.palletsprojects.com/en/1.1.x/tutorial/database/ and https://flask.palletsprojects.com/en/1.1.x/patterns/sqlite3/ to know more about database access inside a flask app.

More on reddit.com
🌐 r/flask
3
2
April 25, 2020
🌐
GitHub
github.com › robmarkcole › HASS-data-detective › issues › 152
AttributeError: 'Engine' object has no attribute 'execute' when excuting detective.HassDatabase(db_url) · Issue #152 · robmarkcole/HASS-data-detective
March 29, 2023 - ......... /site-packages/detective/core.py:73), in HassDatabase.perform_query(self, query, **params) 71 """Perform a query.""" ... ---> 73 return self.engine.execute(query, params) 74 except: 75 print(f"Error with query: {query}") AttributeError: 'Engine' object has no attribute 'execute'
Author   ZZDDD
🌐
GitConnected
levelup.gitconnected.com › how-to-fix-attributeerror-optionengine-object-has-no-attribute-execute-in-pandas-eb635fbb89e4
How to Fix AttributeError: ‘OptionEngine’ object has no attribute ‘execute’ in Pandas | Level Up Coding
February 12, 2023 - More specifically, when calling read_sql_query with an SQL query and a SQLAlchemy engine we should observe the following AttributeError: line 1405, in execute return self.connectable.execution_options().execute(*args, **kwargs) AttributeError: 'OptionEngine' object has no attribute 'execute'
🌐
Great Expectations
discourse.greatexpectations.io › gx core support
Unable to Validate Expectation Suit with PostgresSQL (No execute Attribute for Engine Object) - GX Core Support - Great Expectations
February 9, 2023 - Good Day GEX Community, We have been testing Great Expectation for PostgresSQL for our organisation. We are successfully able to creating data source and expectation suit but upon performing the validation, we are facing the issue of not having execute attribute for the Engine object sqlalchemy_batch_data.py of the library.
🌐
Google
discuss.google.dev › google cloud › database
AttributeError: 'Engine' object has no attribute 'character_set_name' - Database - Google Developer forums
December 22, 2023 - I am running a python app on GCP app engine which connects to cloud SQL database (mySQL). But there is an error in GCP logs that I am unable to resolve, File “/layers/google.python.pip/pip/lib/python3.9/site-packages/sqlalchemy/dialects/mysql/mysqldb.py”, line 161, in on_connect charset_name = conn.character_set_name() AttributeError: ‘Engine’ object has no attribute ‘character_set_name’ Here is the code I am using to establish connection: def connect_with_connector() -> sqlalchemy.engine.bas...
🌐
SQLAlchemy
docs.sqlalchemy.org › en › 13 › core › connections.html
Working with Engines and Connections — SQLAlchemy 1.3 Documentation
Overall, the usage of “bound metadata” has three general effects: SQL statement objects gain an Executable.execute() method which automatically locates a “bind” with which to execute themselves. The ORM Session object supports using “bound metadata” in order to establish which Engine should be used to invoke SQL statements on behalf of a particular mapped class, though the Session also features its own explicit system of establishing complex Engine/ mapped class configurations.
Find elsewhere
🌐
YouTube
youtube.com › watch
AttributeError and Not an executable object error in SQLAlchemy - YouTube
Updated Source is available herehttps://www.plus2net.com/python/mysql-sqlalchemy.phphttps://www.plus2net.com/python/sqlite-connection.php
Published   July 30, 2023
🌐
GitHub
github.com › georgevbsantiago › qsacnpj › issues › 35
AttributeError: 'Engine' object has no attribute 'execute' · Issue #35 · georgevbsantiago/qsacnpj
May 19, 2023 - AttributeError: 'Engine' object has no attribute 'execute'#35 · Copy link · LucasLaporti · opened · on May 20, 2023 · Issue body actions · Boa noite! Alguém poderia me ajudar sobre esse erro que apareceu na hora de rodar o script? No one assigned · No labels · No labels ·
🌐
Whoolatoys
whoolatoys.ca › Trending › attributeerror-engine-object-has-no-attribute-execute
attributeerror: 'engine' object has no attribute 'execute'
November 16, 2024 - Incorrect Usage of the Engine Object: The SQLAlchemy engine object is designed to create connections, not to execute SQL commands directly. Using it incorrectly can lead to this error.
🌐
Yandex
yandex.ru › video › preview › 1850053402174605908
AttributeError: 'Engine' object has no attribute 'execute' when ...
AttributeError: 'Engine' object has no attribute 'execute' when trying to run sqlalchemy in pytho
🌐
Lightrun
lightrun.com › answers › gunthercox-chatterbot-attributeerror-mysqlconnection-object-has-no-attribute-execute
AttributeError: 'MySQLConnection' object has no attribute 'execute'
Traceback (most recent call last): File "D:/user.one/project/_analytics/Analytics/server.py", line 134, in <module> chatterbot = make_chatterbot() File "D:/user.one/project/_analytics/Analytics/server.py", line 128, in make_chatterbot my_engine = create_engine(CONNECTION_STRING, poolclass=NullPool).connect() File "D:\user.one\personal\_python\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 2102, in connect return self._connection_cls(self, **kwargs) File "D:\user.one\personal\_python\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 90, in __init__ if connection is not
🌐
Whoolatoys
whoolatoys.ca › Trending › attributeerror-engine-object-has-no-attribute-cursor
attributeerror: 'engine' object has no attribute 'cursor'
November 17, 2024 - SQLAlchemy typically abstracts away the need for direct cursor manipulation. The AttributeError happens because you're trying to use the cursor attribute as if it were part of the Engine object.
🌐
Illumine
illumine.tw › xkldimedn11 › attributeerror-engine-object-has-no-attribute-cursor
attributeerror: 'engine' object has no attribute 'cursor'
October 1, 2024 - Create a connection using the engine.connect() method, or use a Session object if you're working with ORM. Use the execute() method directly on the connection. Here’s a common situation that leads to this error: from sqlalchemy import create_engine # Create an engine engine = create_engine('sqlite:///example.db') # Incorrect usage that will lead to the error cursor = engine.cursor() # This will raise AttributeError
🌐
Millers Pub Nanaimo
millerspubnanaimo.ca › zerosixai › attributeerror-engine-object-has-no-attribute-cursor
attributeerror: 'engine' object has no attribute 'cursor'
December 13, 2024 - The AttributeError: 'Engine' object has no attribute 'cursor' typically stems from these scenarios: ... The most frequent cause is attempting to use the Engine directly where a Connection is required.
🌐
Yamakawa
yamakawa.com.tw › vertic328 › attributeerror-engine-object-has-no-attribute-cursor1
attributeerror: 'engine' object has no attribute 'cursor'
December 13, 2024 - This code snippet tries to get a cursor from the engine object itself, leading to the AttributeError. ... Establish a connection: Get a connection object from your engine using engine.connect(). Execute your query: Use the connection's execute() method to run your SQL query.
🌐
Relicoutfitters
relicoutfitters.ca › educationai › attributeerror-engine-object-has-no-attribute-execute
attributeerror: 'engine' object has no attribute 'execute'
December 13, 2024 - The dreaded AttributeError: 'engine' ... Object-Relational Mappers (ORMs). This error means your code is trying to call an execute() method on an object that doesn't possess such a method....
🌐
Haciendasantateresa
haciendasantateresa.ca › intipya › attributeerror-engine-object-has-no-attribute-cursor
attributeerror: 'engine' object has no attribute 'cursor'
November 11, 2024 - You can use it to execute raw SQL queries and manage transactions. Engine: The Engine object is primarily used for creating connections to the database and configuring settings. ... from sqlalchemy import create_engine engine = create_engine('postgresql://user:password@host:port/database') cursor = engine.cursor() # AttributeError: 'engine' object has no attribute 'cursor'
🌐
Yundingvilla
yundingvilla.com.tw › intipya › attributeerror-engine-object-has-no-attribute-execute
attributeerror: 'engine' object has no attribute 'execute'
October 21, 2024 - While the engine orchestrates database interactions, it's not designed to execute queries directly. ... The mistake: You're trying to execute a query using the engine object, which is incorrect.