4

I know we can read sql using different packages than mysql.connector but since I only know mysql.connector, I want to use it to read a table from sql and save it as dataframe in pandas. I have the following as my code.

import mysql.connector
import pandas as pd

mydb = mysql.connector.connect(
    host = 'localhost',
    user = 'root',
    passwd = '*',
    database = 'mydatabase'
)

mycursor = mydb.cursor()

query = "SELECT * FROM my table"
df = pd.read_sql(query, mycursor)

I am not sure about the last line, that is df = pd.read_sql(query, mycursor). I think I am missing some arguments here. Can you please help me with that?

2 Answers 2

6

You need to replace df = pd.read_sql(query, mycursor) with df = pd.read_sql_query(query, mydb) because you want to make a DataFrame using a query (make sure to pass mydb not mycursor).

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

1 Comment

I get this error: AttributeError: 'CMySQLCursor' object has no attribute 'cursor'. It does not work.
4

TRY THIS CODE

import mysql.connector as sql

import pandas as pd

db_connection = sql.connect(host='hostname', database='db_name', 
user='username', password='password')

df = pd.read_sql('SELECT * FROM table_name', con=db_connection)

2 Comments

i get UserWarning: pandas only supports SQLAlchemy connectable (engine/connection) or database string URI or sqlite3 DBAPI2 connection. Other DBAPI2 objects are not tested. Please consider using SQLAlchemy. df = pd.read_sql_query(q, mydb)
@Raksha This is just a warning and probably works. SQLAlchemy has problems with Python 3

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.