PadhaiTime Logo
Padhai Time

Reading Data from Database

Data can reside in the database too. Python provides libraries by which we can connect with the database and can read the required tables.

A Database can be of any type, few examples are:

  • MySQL
  • MSSQL
  • MongoDB
  • Cosmos DB
  • DynamoDB

And python provides libraries specific to each of the databases. As per our requirement, we can use the specific library to connect with the database. For this tutorial purpose, we are going to use MySQL database and its corresponding python library to read the data.

Here we can see

Schema/Database is “test”

Table is “titanic_data”

undefined

To get data from a database, first we need to connect our python to it. To connect python to a database, we need to know 4 parameters:

IP of Server, User Name, User Password and Port on which server instance is running

For this tutorial, we are using local mysql database and below are its details:

host_name = 'localhost' # You can use 127.0.0.1 also instead of localhost

host_port = '3306' # 3306 is the port on which mysql instance is running

user_name = 'root' # root is the user

user_pass = 'user@123' # password for the username - for authentication

And there is a library called ‘pymysql’ which allows us to connect python with mysql database.

Below snapshot explains clearly how we can read data from a table.

undefined

When we connect with a database, one connection gets created and it is recommended to close the connection once our intended work is done as shown above.

Bengaluru, India
contact.padhaitime@gmail.com
  • We collect cookies and may share with 3rd party vendors for analytics, advertising and to enhance your experience. You can read more about our cookie policy by clicking on the 'Learn More' Button. By Clicking 'Accept', you agree to use our cookie technology.
    Our Privacy policy can be found by clicking here