Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store mySQL query result into pandas DataFrame with pymysql?

I'm trying to store a mySQL query result in a pandas DataFrame using pymysql and am running into errors building the dataframe. Found a similar question here and here, but it looks like there are pymysql-specific errors being thrown:

import pandas as pd
import datetime
import pymysql

# dummy values 
connection = pymysql.connect(user='username', password='password', databse='database_name', host='host')

start_date = datetime.datetime(2017,11,15)
end_date = datetime.datetime(2017,11,16)

try:
    with connection.cursor() as cursor:
    query = "SELECT * FROM orders WHERE date_time BETWEEN %s AND %s"

    cursor.execute(query, (start_date, end_date)) 

    df = pd.DataFrame(data=cursor.fetchall(), index = None, columns = cursor.keys())
finally:
    connection.close()

returns: AttributeError: 'Cursor' object has no attribute 'keys'

If I drop the index and columns arguments:

try:
    with connection.cursor() as cursor:
    query = "SELECT * FROM orders WHERE date_time BETWEEN %s AND %s"

    cursor.execute(query, (start_date, end_date)) 

    df = pd.DataFrame(cursor.fetchall())
finally:
    connection.close()

returns ValueError: DataFrame constructor not properly called!

Thanks in advance!

like image 477
msoderstrom Avatar asked Nov 16 '17 11:11

msoderstrom


People also ask

What does Pymysql fetchAll return?

PyMySQL fetchAll The fetchAll method retrieves all (remaining) rows of a query result, returning them as a sequence of sequences. In the example, we retrieve all cities from the database table. This SQL statement selects all data from the cities table.

Which method is used to fetch the data from MySQL database through DataFrame?

The fetchone() method is internally used by a fetchall() and fetchmany() to fetch rows.


2 Answers

Use Pandas.read_sql() for this:

query = "SELECT * FROM orders WHERE date_time BETWEEN ? AND ?"
df = pd.read_sql(query, connection,  params=(start_date, end_date))
like image 169
MaxU - stop WAR against UA Avatar answered Oct 17 '22 22:10

MaxU - stop WAR against UA


Try This:

import pandas as pd
import pymysql

mysql_connection = pymysql.connect(host='localhost', user='root', password='', db='test', charset='utf8')
                    
sql = "SELECT * FROM `brands`"
df = pd.read_sql(sql, mysql_connection, index_col='brand_id')
print(df)
like image 21
Alexandre Crivellaro Avatar answered Oct 17 '22 22:10

Alexandre Crivellaro