1.
Python and MySQL Integration
To connect Python with MySQL, you typically use libraries such as:
mysql-connector-python: A library provided by MySQL.
PyMySQL: A lightweight library for MySQL.
SQLAlchemy: An Object Relational Mapper (ORM) for complex applications.
Installation:
bash
Copy code
pip install mysql-connector-python
pip install pymysql
pip install sqlalchemy
2. Basic Operations
Connecting to MySQL
python
Copy code
import mysql.connector
# Establish connection
conn = mysql.connector.connect(
host="localhost",
user="root",
password="your_password",
database="your_database"
)
# Create a cursor
cursor = conn.cursor()
Executing SQL Queries
Creating a Table:
python
Copy code
cursor.execute("""
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
age INT,
course VARCHAR(50)
)
""")
Inserting Data:
python
Copy code
cursor.execute("INSERT INTO students (name, age, course) VALUES (%s, %s,
%s)",
("Suraj", 21, "BCA"))
conn.commit()
Fetching Data:
python
Copy code
cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()
for row in rows:
print(row)
Updating Data:
python
Copy code
cursor.execute("UPDATE students SET course = %s WHERE name = %s",
("MCA", "Suraj"))
conn.commit()
Deleting Data:
python
Copy code
cursor.execute("DELETE FROM students WHERE name = %s", ("Suraj",))
conn.commit()
Closing the Connection
python
Copy code
cursor.close()
conn.close()
3. Advanced Topics
Using Prepared Statements
To prevent SQL injection:
python
Copy code
query = "SELECT * FROM students WHERE name = %s"
cursor.execute(query, ("Suraj",))
Using SQLAlchemy for ORM
python
Copy code
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# Database URL
engine =
create_engine('mysql+pymysql://root:your_password@localhost/your_database')
Base = declarative_base()
# Define a model
class Student(Base):
__tablename__ = 'students'
id = Column(Integer, primary_key=True)
name = Column(String(100))
age = Column(Integer)
course = Column(String(50))
# Create tables
Base.metadata.create_all(engine)
# Create a session
Session = sessionmaker(bind=engine)
session = Session()
# Add a new student
new_student = Student(name="Suraj", age=21, course="