Category: python
MySQL Connectivity in Python
Published on 24 Jul 2026
Explanation
Python can connect to MySQL databases using the mysql-connector-python library. This library allows Python applications to perform database operations such
Code:
# Install MySQL Connector
# pip install mysql-connector-python
import mysql.connector
print('MySQL Connector Installed Successfully')
Explanation
To interact with a MySQL database, a connection must first be established using the mysql.connector.connect() function. The connection requires details
Code:
import mysql.connector
connection = mysql.connector.connect(
host='localhost',
user='root',
password='password',
database='school_db'
)
if connection.is_connected():
print('Connected to MySQL Successfully')
Explanation
After establishing a connection, a cursor object is created using the cursor() method. The cursor executes SQL statements such as
Code:
import mysql.connector
connection = mysql.connector.connect(
host='localhost',
user='root',
password='password',
database='school_db'
)
cursor = connection.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS students (
id INT PRIMARY KEY,
name VARCHAR(100),
marks INT
)
''')
cursor.execute("INSERT INTO students VALUES (101, 'John', 85)")
connection.commit()
print('Record Inserted Successfully')
Explanation
The SELECT statement is used to retrieve records from a database table. The execute() method runs the SQL query, and
Code:
import mysql.connector
connection = mysql.connector.connect(
host='localhost',
user='root',
password='password',
database='school_db'
)
cursor = connection.cursor()
cursor.execute('SELECT * FROM students')
records = cursor.fetchall()
for student in records:
print(student)
Explanation
CRUD stands for Create, Read, Update, and Delete, which are the four basic operations performed on database records. Most business
Code:
import mysql.connector
connection = mysql.connector.connect(
host='localhost',
user='root',
password='password',
database='school_db'
)
cursor = connection.cursor()
# Insert
cursor.execute(
'INSERT INTO students (id, name, marks) VALUES (%s, %s, %s)',
(102, 'Alice', 90)
)
# Update
cursor.execute(
'UPDATE students SET marks = %s WHERE id = %s',
(95, 102)
)
# Delete
cursor.execute(
'DELETE FROM students WHERE id = %s',
(102,)
)
connection.commit()
# Read
cursor.execute('SELECT * FROM students')
for row in cursor.fetchall():
print(row)
cursor.close()
connection.close()