Hackforge Academy

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()

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community