Category: python
MySQL connector package for Python
Published on 05 Mar 2026
Explanation
First, install the MySQL connector package
for Python.
This library allows Python to
communicate with MySQL.
Code:
pip install mysql-connector-python
Explanation
Import the mysql.connector module
to use MySQL connection features.
Code:
import mysql.connector
Explanation
Create a connection to the MySQL database by
providing
host
username
password and
database name.
Code:
conn = mysql.connector.connect(
host='localhost',
user='root',
password='root',
database='testdb'
)
Explanation
Check whether the connection is established
successfully.
Code:
if conn.is_connected():
print('Connected successfully to MySQL')
Explanation
Create a cursor object to execute SQL
queries.
Code:
cursor = conn.cursor()
Explanation
Execute a SQL query and fetch all records
from the 'users' table.
Code:
cursor.execute('SELECT * FROM users')
result = cursor.fetchall()
print(result)
Explanation
Always close the cursor and connection
after completing database operations to
prevent resource leaks.
Code:
cursor.close() conn.close()