Created
November 5, 2015 15:24
-
-
Save jmquintana79/d0920234e9f49d689577 to your computer and use it in GitHub Desktop.
mysql table to pandas dataframe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import MySQLdb | |
import pandas as pd | |
#### EXECUTE MYSQL QUERY function | |
def dfquery( query , value_index_col ): | |
# get mysql connection | |
con = MySQLdb.connect(host='127.0.0.1',user='xxx',passwd='xxx') | |
# execute query and saving data in dataframe | |
try: | |
dfresult = pd.read_sql(query, con,index_col=value_index_col) | |
except: | |
dfresult = pd.read_sql(query, con) | |
# close mysql connection | |
con.close() | |
return dfresult | |
## MYSQL DATABASE TO DATAFRAME | |
# mysql query parameters | |
dbname = "database" | |
tablename = "table" | |
fieldname = "field" | |
# build query (simple select) | |
query = "SELECT id,time," + fieldname + " FROM " + dbname + "." + tablename | |
# execute query | |
dfinput = dfquery( query ,'id' ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment