Introduction To Connectivity


☞ When we design real-life applications, we need to manipulate data stored in a database through an application designed by us. Here we are developing Python applications and will connect to a MySQL database from within a Python script.

MySQL.connector module of Python is used to connect MySQL databases with the python programs.

☞ It uses python standard library and has no dependencies.

☞ To understand the concept, we will create a real-life application i.e. Student Management System. In this application we will connect Python and MySQL, and will perform various operations such as creating a database, creating a table, inserting student details, fetching student details, modifying student details, deleting student details.


Steps to create database connectivity application

Step 1 : Import the modules required for database programming i.e. mysql.connector module

Syntax :

import mysql.connector
or
import mysql.connector as m

Step 2 : Open a connection to database using connect(host= ‘.....’, user= ‘.....’, password= ‘.....’) of mysql.connector module
where,
host - database server hostname or IP address
user - username on MySQL
password - Password on MySQL

Syntax :

<connection_object>=mysql.connector.connect(host= ‘.....’, user= ‘.....’, password= ‘.....’)
or
<connection_object>=m.connect(host= ‘.....’, user= ‘.....’, password= ‘.....’)

Step 3 : Create a cursor object using cursor() function

Syntax :

<cursor_object> = <connection_object>.cursor()

Step 4 : Execute a query using execute() function

Syntax :

<cursor_object>.execute(<sql_command_as_string>)

Step 5 : Clean up the environment

Syntax :

<connection_object>.close()