How to connect Database in Python?


Most of the applications need to be integrated or connected with a database for performing certain relevant operations. The majority of projects require database connectivity to store certain data about the users. MySQL Database can be integrated with the Python applications.

To connect MySQL database, we need to have it installed on our system. We need MySQL Connector to establish connection with the database. We can install MySql Connector using the following command.

python –m pip install mysql-connector-python

This will install the MySQL Connector which is used to connect the python project or application to a database.

Create a connection

First of all, it is required to create a connection with the database. Later we can execute sql commands to perform certain database operations. The username and password of your sql database is used.

Example

import mysql.connector

mydatabase=mysql.connector.connect(
   host="localhost",
   user="your_user_name",
   password="your_password"
   database=”database_name”
)

The connection to the database is made. The database name is included in the connect() when you need to connect to a specific database. Now, you can execute sql commands to perform database operations.

Create cursor object

The cursor object is created using the cursor() function. The cursor object is important to execute database queries.

cursor_name=connection_name.cursor()

Example

import mysql.connector

mydatabase=mysql.connector.connect(
   host="localhost",
   user="your_user_name",
   password="your_password"
   database=”database_name”
)
mycsr=mydatabase.cursor()

Now, the connection is established and cursor object is created. We can execute any SQL query on this database now using execute() function.

Updated on: 11-Jun-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements