Reading data from MySQL database in Python

In order to read data from MySQL in Python, the libraries needed are sqlalchemy, mysql.connector and pymysql.

You can install these libraries using below commands in a cell of your Jupyter notebook. These commands can also be executed in command prompt without the exclamation “!”.

Once the libraries are installed, it is a two step process to connect to mysql database.

  • Establishing Connection: A connection object is created using create_engine() function from sqlalchemy library. This stores all the information required to login to the database.
  • Run SQL query: Any valid sql query(simple or complex both) can be executed on the database with the help of above connection and pandas function read_sql()

Below snippet connects to the mysql database and runs a given query. Change the database credentials based on your system.

Sample Output:

Reading Data from MySql database in python
Reading Data from MySql database in python

Author Details
Lead Data Scientist
Farukh is an innovator in solving industry problems using Artificial intelligence. His expertise is backed with 10 years of industry experience. Being a senior data scientist he is responsible for designing the AI/ML solution to provide maximum gains for the clients. As a thought leader, his focus is on solving the key business problems of the CPG Industry. He has worked across different domains like Telecom, Insurance, and Logistics. He has worked with global tech leaders including Infosys, IBM, and Persistent systems. His passion to teach inspired him to create this website!

Leave a Reply!

Your email address will not be published. Required fields are marked *