Step 1 — Install MySQL Connector
pip install mysql-connector-python
Step 2 — Connect Python to MySQL
import [Link]
db = [Link](
host="localhost",
user="root",
password="your_password",
database="book"
)
print("Connected successfully")
Step 3 — Create Cursor
#What is a Cursor in Python?
In Python database programming, a cursor is an object that lets you send SQL commands
to a database and receive the results.
Why is Cursor Needed?
A database connection alone cannot execute queries.
The cursor is the tool that:
Executes SQL statements
Fetches records
How Cursor Works
[Link]() → creates cursor
[Link]() → runs SQL query
[Link]() → gets all rows
[Link]() → gets one row
cursor = [Link]()
Step 4 — Fetch Data from orders Table
[Link]("SELECT * FROM orders")
result = [Link]()
for row in result:
print(row)
Step 5 — Insert Data into orders
# (%s) Means a value will be provided here later.
sql = "INSERT INTO orders (order_id, customer_name, amount) VALUES (%s, %s,
%s)"
data = (101, "Rahul", 2500)
[Link](sql, data)
[Link]()
print([Link], "record inserted")
Step 6 — Fetch Again After Insert
[Link]("SELECT * FROM orders")
for row in [Link]():
print(row)
Step 7 — Close Connection
[Link]()
[Link]()
Sample Output
Connected successfully
(1, 'Amit', 1500)
(2, 'Neha', 2000)
1 record inserted
(1, 'Amit', 1500)
(2, 'Neha', 2000)
(101, 'Rahul', 2500)
Table create code
. Create Table – orders
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_name VARCHAR(100),
amount DECIMAL(10,2)
);
Insert Records
INSERT INTO orders (order_id, customer_name, amount)
VALUES (1, 'Ravi Kumar', 2500.50);
INSERT INTO orders (order_id, customer_name, amount)
VALUES (2, 'Anita Sharma', 1800.00);
INSERT INTO orders (order_id, customer_name, amount)
VALUES (3, 'Pramod Singh', 3200.75);