Skip to content

Instantly share code, notes, and snippets.

@jmquintana79
Created November 5, 2015 15:24
Show Gist options
  • Save jmquintana79/d0920234e9f49d689577 to your computer and use it in GitHub Desktop.
Save jmquintana79/d0920234e9f49d689577 to your computer and use it in GitHub Desktop.
mysql table to pandas dataframe
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