Interfacing Python with MySQL
Python provides strong support for working with databases. MySQL is one of the most widely used
relational databases. By using the MySQL Connector or other libraries, Python can easily interact
with MySQL to perform operations like inserting, updating, deleting, and retrieving data.
Steps to Interface Python with MySQL:
1 Install MySQL server and set up a database.
2 Install Python MySQL connector using: pip install mysql-connector-python
3 Import the connector module in your Python program.
4 Establish a connection using [Link]() with host, user, password, and
database details.
5 Create a cursor object to execute SQL queries.
6 Execute queries like CREATE, INSERT, SELECT, UPDATE, DELETE using the cursor.
7 Fetch results using fetchone(), fetchall(), etc.
8 Close the cursor and connection after completing operations.
Example Python Code:
import [Link]
# Establish connection
conn = [Link](
host="localhost",
user="root",
password="your_password",
database="testdb"
)
cursor = [Link]()
# Create table
[Link]("CREATE TABLE IF NOT EXISTS students (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(
# Insert data
[Link]("INSERT INTO students (name, age) VALUES (%s, %s)", ("John", 20))
[Link]()
# Retrieve data
[Link]("SELECT * FROM students")
for row in [Link]():
print(row)
# Close connection
[Link]()
[Link]()
With this setup, Python can effectively communicate with MySQL to perform all necessary database
operations. This is essential for building real-world applications that require data persistence and
management.