J'essaie de stocker un résultat de requête mySQL dans un pandas DataFrame en utilisant pymysql
et je rencontre des erreurs lors de la construction du dataframe. J'ai trouvé une question similaire ici = et ici , mais il semble qu'il y ait des erreurs spécifiques à pymysql
:
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()
retour: AttributeError: 'Cursor' object has no attribute 'keys'
Si je laisse tomber les arguments index
et columns
:
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()
retour ValueError: DataFrame constructor not properly called!
Merci d'avance!
Utilisez Pandas.read_sql () pour cela:
query = "SELECT * FROM orders WHERE date_time BETWEEN ? AND ?"
df = pd.read_sql(query, connection, params=(start_date, end_date))