How to Connect MySQL Database in Python?

  2081 views   1 year ago Python

In this article, I will share with you how to connect the MySQL database in Python using mysql.connector. as you know if you want to make web applications in python the first and very important step is to use any database to store all the records. so, here in this article, I show you how to use the MySQL database in Python.

Python provides mysql.connector library for connection with MySQL. so, here we also use this library and make connections between MySQL and Python.

After, the connection successfully then you can store, fetch, and update any record in the database help of Python code.


import mysql.connector
from mysql.connector import Error

    connection = mysql.connector.connect(host='localhost',
    if connection.is_connected():
        db_Info = connection.get_server_info()
        print("Connected to MySQL Server version ", db_Info)
        cursor = connection.cursor()
        cursor.execute("select database();")
        record = cursor.fetchone()
        print("You're connected to database: ", record)

except Error as e:
    print("Error while connecting to MySQL", e)
    if (connection.is_connected()):
        print("MySQL connection is closed")

i hope you like this article.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]