Python MySQL Connector is a powerful library that enables Python programs to interact with MySQL databases. It provides a seamless way to connect, query, and manipulate data stored in MySQL servers.
To get started, install the MySQL Connector using pip:
pip install mysql-connector-python
Establishing a connection is the first step in working with MySQL databases:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
print("Connected to MySQL database!")
Once connected, you can execute SQL queries using a cursor object:
cursor = mydb.cursor()
# Execute a SELECT query
cursor.execute("SELECT * FROM customers")
# Fetch all results
results = cursor.fetchall()
for row in results:
print(row)
To insert data into a table, use an INSERT query:
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John Doe", "Highway 21")
cursor.execute(sql, val)
mydb.commit()
print(cursor.rowcount, "record inserted.")
To further enhance your database skills with Python, explore these related topics:
By mastering Python MySQL Connector, you'll be able to efficiently interact with MySQL databases, opening up possibilities for robust data-driven applications. Remember to always sanitize inputs and follow security best practices when working with databases.