Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas read_sql() - AttributeError: 'Engine' object has no attribute 'cursor'

I am trying to read data from MySQL query using pandas read_sql() method with python3+sqlalchemy+pymysql

I tried to follow the following tutorials -

https://pythondata.com/quick-tip-sqlalchemy-for-mysql-and-pandas/

https://www.youtube.com/watch?v=M-4EpNdlSuY

https://www.programcreek.com/python/example/101381/pandas.read_sql

Everything just looks good with the code

import pandas
import sqlalchemy
engine = sqlalchemy.create_engine('mysql+pymysql://root:[email protected]:3306/mydatabase')
df = pandas.read_sql("SELECT * FROM persons", con = engine)

Receiving following error -

AttributeError: 'Engine' object has no attribute 'cursor'

When I tried to pass the 'connection' variable instead of the 'engine', like below -

import pandas
import sqlalchemy
engine = sqlalchemy.create_engine('mysql+pymysql://root:[email protected]:3306/mydatabase')
connection = engine.connect()
df = pandas.read_sql("SELECT * FROM persons", con = connection)

it says -

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

What am I doing wrong?

like image 412
Adi Avatar asked Mar 23 '19 14:03

Adi


2 Answers

Reference - https://github.com/pandas-dev/pandas/issues/23030#issuecomment-428140488

The problem went away when I

  • Saved my workbook
  • Restarted the PC
  • Reloaded

It seems like something was cached. I could use read_sql() and other pandas sql functions by passing 'engine' reference -

import pandas
import sqlalchemy
engine = sqlalchemy.create_engine('mysql+pymysql://root:[email protected]:3306/mydatabase')
df = pandas.read_sql("SELECT * FROM persons", con = engine)
like image 121
Adi Avatar answered Sep 21 '22 07:09

Adi


I think you are looking for pyodbc and sqlalchemy is another way of query db , check with https://towardsdatascience.com/sqlalchemy-python-tutorial-79a577141a91

import sqlalchemy as sq
engine = sq.create_engine('mysql+pymysql://root:[email protected]:3306/mydatabase')
connection = engine.connect()
metadata = sq.MetaData()
persons = sq.Table('persons', metadata, autoload=True, autoload_with=engine)

Ret = connection.execute(sq.select([persons]))
youdf=pd.DataFrame(Ret.fetchall())
like image 37
BENY Avatar answered Sep 21 '22 07:09

BENY