How to connect python with MySQL database?

Please guide me, how to connect python with MySQL database.

Before using mysql, you need to install mysql.connector module. Use the below command to install it:

$ sudo apt-get install python3-mysql.connector

Above example is for python3 and same can be used for python2 also.

Get a quick reference with an example below:

import mysql.connector

cn = mysql.connector.connect(user='root', password='admin@123',
                              host='127.0.0.1',
                              database='python_test')

cursor = cn.cursor()
cursor.execute("select * from test")
result = cursor.fetchall()
for r in result:
    print(r[0], " - ", r[1])

cn.close()