Programming with Python

  1. Home
  2. Docs
  3. Programming with Python
  4. Database in Python
  5. Connections

Connections

A typical file processing system suffers from some major limitations like Data redundancy, data inconsistency, unsharable data, unstandardized data, insecure data, incorrect data, etc.

On the other hand, a database system overcomes all these limitations and ensures continuous efficiency.

Relational Database- Data are stored in form of tables also known as relations. Generally each table represent one entity.

Data => Database => Relational Database => Tables or entities => Tuple or record => Attributes.

Relational Database Management system RDBMS is an application software for creating and managing relational databases. It makes us possible for us to create, read, update and delete data from a database.

MySQL is a popular RDBMS software which use a client server model. So here we will see how to connect database in python.

MySQL, is an open source relational database management system. It is based on the structure query language (SQL), which is used for adding, removing, and modifying information in the database.

Installation of MySQL:-

  • Open the command prompt
  • Type the following command.
  • pip install MySQL -python
  • Successfully install MySQL database.

You can easily import MySQL in python and use it.

syntax:-

import MySQLdb

We can create a new table by importing mysql.connector. To create a database in MySQL, we can use the “CREATE DATABASE” statement. Before that, we need to import mysql.connector and provide the required connection.

There are the following steps to connect a python application to our database.

  • Import mysql.connector module
  • Create the connection object.
  • Create the cursor object
  • Execute the query

syntax:-

import mysql.connector
db_connection = mysql.connector.connect
(    host="hostname",
     user="root", 
     password="pin",
     database="name_of_database"
)

We have some function which has some specific work:-

  • cursor.execute()- This is used to execute SQL queries.
  • cursor.close()- It is used to close the cursor object.
  • connection.close()- It is used to close MySQL database after the work is done

This is how we establish connection of database in python.

Was this article helpful to you? Yes No

How can we help?