AttributeError: 'Engine' object has no attribute 'execute' when trying to run sqlalchemy in python to manage my SQL database

Question:

I have the following line of code that keeps giving me an error that Engine object has no object execute. I think I have everything right but no idea what keeps happening. It seemed others had this issue and restarting their notebooks worked. I’m using Pycharm and have restarted that without any resolution. Any help is greatly appreciated!

import pandas as pd
from sqlalchemy import create_engine, text
import sqlalchemy
import pymysql


masterlist = pd.read_excel('Masterlist.xlsx')

user = 'root'
pw = 'test!*'
db = 'hcftest'

engine = create_engine("mysql+pymysql://{user}:{pw}@localhost:3306/{db}"
                           .format(user=user, pw=pw, db=db))


results = engine.execute(text("SELECT * FROM companyname;"))

for row in results:
    print(row)
Asked By: novawaly

||

Answers:

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

Answered By: jonathan-dufault-kr
from .. import db

def get():

    sql_statement = 
        """
            SELECT *
        """

    with db.engine.begin() as conn:
        response = conn.exec_driver_sql(sql_statement).all()
    
    return response
Answered By: James Prentice
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.