Python - Fetch data from MySQL to Pandas

By xngo on April 4, 2019

Here is how to fetch data from MySQL table into Pandas data feed. In the code below, make sure to change the following variables to match your settings:

  • host
  • username
  • password
  • db_name
  • sql_query
#!/usr/bin/python3
import mysql.connector
 
import pandas as df
import pandas.io.sql as psql
 
# Get MySQL connection.
host="localhost"
username="root2"
password="password"
db_name="test_db_name"
connection = mysql.connector.connect(
                                      host=host,
                                      user=username,
                                      passwd=password,
                                      database=db_name
                                    )
 
# Fetch data into pandas.
sql_query = "SELECT * FROM Price LIMIT 10"
df = psql.read_sql(sql_query, connection)
print(df)

Output

   ticker_id        date       open        low       high      close  adj_close   volume
0          1  1962-01-02  71.550003  70.709999  71.959999  70.959999  70.959999  3120000
1          1  1962-01-03  70.959999  70.379997  71.480003  71.129997  71.129997  3590000
2          1  1962-01-04  71.129997  70.449997  71.620003  70.639999  70.639999  4450000
3          1  1962-01-05  70.639999  69.349998  70.839996  69.660004  69.660004  4630000
4          1  1962-01-08  69.660004  68.169998  69.839996  69.120003  69.120003  4620000
5          1  1962-01-09  69.120003  68.830002  69.930000  69.150002  69.150002  3600000
6          1  1962-01-10  69.150002  68.620003  69.580002  68.959999  68.959999  3300000
7          1  1962-01-11  68.959999  68.570000  69.540001  69.370003  69.370003  3390000
8          1  1962-01-12  69.370003  69.230003  70.169998  69.610001  69.610001  3730000
9          1  1962-01-15  69.610001  69.059998  69.959999  69.470001  69.470001  3450000

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.