Python MySQL Database Connection Example

Published On: 15/06/2022 | Category: Python

Hi Dev,

I will explain step by step tutorial python mysql database connection example. Here you will learn python mysql database connection explained with examples. Here you will learn python mysql database connection example apache. you will learn python mysql database connection example mysql-connector-python. Alright, let’s dive into the steps.

So, python mysql connector is a python driver that helps to integrate python and mysql. this python mysql library allows the conversion between python and mysql data types.

So let's see the below example:

Example

Next install the Python-mysql-connector module, one must have Python and PIP, preinstalled on their system. If Python and pip are already installed type the below command in the terminal.

pip3 install mysql-connector-python

So, we can next connecting to mysql server using the connect() method.

main.py
# importing required libraries
import mysql.connector
  
dataBase = mysql.connector.connect(
  host ="localhost",
  user ="root",
  passwd ="root"
)
 
print(dataBase)
  
# Disconnecting from the server
dataBase.close()
Run Example
python3 main.py
Output
<mysql.connector.connection_cext.CMySQLConnection object at 0x7fb611e5e220>

It will help you....