sending an email through gmail using python

How to Connect MySQL Database using Python?

In order to connect your database using python, you need to install a database connector. The easiest way to connect MySQL database using python is by using the MySQL Connector.

Prerequisite:

  1. MySQL server installed in your computer
  2. Created a database, say ‘demo

First, install MySQL connector from the terminal:

pip install mysql-connector

After installation of MySQL connector uses the following code:

import mysql.connector
from mysql.connector import Error
def connect():
    """ Connect to MySQL database """
    conn = None
    try:
        conn = mysql.connector.connect(host='localhost',
                                       database='demo',
                                       user='demo',
                                       password='demo')
        if conn.is_connected():
            print('Connected to MySQL database')
    except Error as e:
        print(e)
    finally:
        conn.close()
if __name__ == '__main__':
    connect()