Python – MySQL Connectivity (Notes)
Introduction
• Database: Organized collection of data.
• MySQL: Popular RDBMS (Relational Database Management System).
• Python-MySQL Connectivity: Connecting Python programs with MySQL to perform operations
(Insert, Update, Delete, Retrieve).
Steps for Python-MySQL Connectivity
1. Import connector module
2. Establish connection
3. Create cursor object
4. Execute SQL query
5. Fetch data (fetchone / fetchall)
6. Process results
7. Commit changes (for Insert/Update/Delete)
8. Close connection
Common MySQL Queries
CREATE TABLE Student (rno INT PRIMARY KEY, name VARCHAR(30), DOB DATE, Fee
FLOAT);
INSERT INTO Student VALUES (1, 'Ravi', '2006-05-10', 6000);
SELECT * FROM Student;
SELECT * FROM Student WHERE Fee > 5000;
UPDATE Student SET Fee = 7000 WHERE rno = 1;
DELETE FROM Student WHERE rno = 1;
Important Functions
• cursor() – creates cursor object
• execute(query) – runs SQL command
• fetchone() – fetch one row
• fetchall() – fetch all rows
• commit() – save changes
• close() – close connection
Error Handling
Using try-except:
try:
con = [Link](... )
cur = [Link]()
[Link]("SELECT * FROM Student")
except Exception as e:
print("Error:", e) 1K_36UOTZY
finally: 3ș3/TYZGRR3S_YWRIUTTKIZUXV_ZNUT33V_S_YWR
[Link]()
3ș3*GZGHGYK3S[YZ3K^OYZ3HKLUXK3IUTTKIZOUT
3ș3'R]G_Y3IRUYK3IUTTKIZOUT3GLZKX3]UXQ
3ș3;YK3IUSSOZ3LUX3INGTMKY
3ș3)[XYUX3OY3[YKJ3ZU3K^KI[ZK3W[KXOKY3GTJ3LKZIN3XKY[RZY