My Python Journey 02 – Connect to MySQL Database from Python

In this article, I am going to connect to my MySQL Database using Python. To connect to MySQL database from Python, we need a specific module such as mysql-connector-python. We need to install this module before we can connect to the server.

To achieve this, I have installed MySQL Server on my Linux server. If you don’t have the server yet, you can follow this guide to install MySQL Server on Ubuntu. Of course, we can use any other distribution or operating system.

Install MySQL Connector

Open Visual Studio Code and click the PowerShell/Terminal tab. Then use this command to install the module.

pip install mysql-connector-python

#Upgrade
pip install mysql-connector-python --upgrade

To connect to MySQL Database using Python, we will need the following information:

  • Host: MySQL server host IP address
  • User: Database user name
  • Password: Database password
  • Database: Database name

Connect to MySQL Using Python

import mysql.connector
db = mysql.connector.connect(user = 'dhani',
                               host = '192.168.2.109',
                               database = 'test',
                               passwd = 'MyPassword')
#Let's connect
if db.is_connected():
    db_info = db.get_server_info()
    print("MySQL Server version is : " + db_info)

#Close the connection to the server
db.close()

When we run this code, it will show the version of the MySQL server in the Terminal console.

MySQL Server version is : 8.0.35