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

pip install mysql-connector-python

 2️⃣ Connecting to MySQL


 

Replace testdb with 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 rows

  • fetchone() → fetch single row


 9️⃣ Updating Data


 


 10️⃣ Deleting Data


 


 11️⃣ Closing Connection



 

Always close cursor and connection after operations.


 12️⃣ Exception Handling


 


 Summary Table

OperationMethod
Connectmysql.connector.connect()
Cursorconn.cursor()
Execute Querycursor.execute(sql)
Insert Multiplecursor.executemany(sql, values)
Fetch Datacursor.fetchall() / cursor.fetchone()
Commit Changesconn.commit()
Close Connectioncursor.close() & conn.close()

You may also like...