Python MySQL Connectivity Introduction

Python can connect with different RDBMS, MYSQL is one of them but there is no ready-made solution available to connect with MySQL. There are two modules that can help us to connect with MySQL
1. MySQLdb
2. MySQL.connector

Here we are considering that you are comfortable with the basics of Python as well as MySQL and you also know how to install Python Modules using the pip command.

Prerequisite for connecting with MySQL

In order to connect Python with MySQL, the following things are required.
1. Host of your MySQL server, IN most of the cases it is Localhost. if you are trying to access your database from other resources than your own machine then this must be the IP address of your server.
2. User Name – The default user name is – root
3. User Password – The password that is used to login into the MySQL server
4. Database – IN the case of MySQl.connector it is optional but in the case of MySQLdb it is compulsory

Syntax using MySQL.connector

import mysql.connector
conn = mysql.connector.connect(host='localhost',

after making the connection with the server. All the types you need to create a cursor using cursor() method to execute all your queries.

cursor = conn.cursor()

Closing connection with MySQL server

The close() method is used to disconnect connection with MySQL


Connecting MySQL with Python using MySQLdb

import MySQLdb
db = MySQLdb.connect("localhost", "root", "", "binarynote" )

NOTE : IN case of MySQLdb there is no need to place placeholder with your arguments.

Print Friendly, PDF & Email

Related Posts

If you like CBSEToaday and would like to contribute, you can also write an article using submit article or mail your article to See your article appearing on the main page and help other students/teachers.