Python MySQL
🐍 Python MySQL
Python can interact with MySQL databases using modules like mysql-connector-python or PyMySQL.
This allows you to store, retrieve, and manipulate data from Python programs.
1️⃣ Install MySQL Connector
2️⃣ Connecting to MySQL
Replace
testdbwith your database name.
3️⃣ Creating a Cursor
Cursor is used to execute SQL queries.
4️⃣ Creating a Database
5️⃣ Creating a Table
6️⃣ Inserting Data
7️⃣ Inserting Multiple Records
8️⃣ Reading Data
fetchall()→ fetch all rowsfetchone()→ fetch single row
9️⃣ Updating Data
10️⃣ Deleting Data
11️⃣ Closing Connection
Always close cursor and connection after operations.
12️⃣ Exception Handling
Summary Table
| Operation | Method |
|---|---|
| Connect | mysql.connector.connect() |
| Cursor | conn.cursor() |
| Execute Query | cursor.execute(sql) |
| Insert Multiple | cursor.executemany(sql, values) |
| Fetch Data | cursor.fetchall() / cursor.fetchone() |
| Commit Changes | conn.commit() |
| Close Connection | cursor.close() & conn.close() |
