Connecting to and using a MySQL-database in Python is easy. Here’s a full example code with comments:
# MySQLdb needs to be installed
import MySQLdb
# Connect to a database
db = MySQLdb.connect(host='localhost', user='username', passwd='password', db='database')
# Create a cursor
cursor = db.cursor()
# Perform a query (returns the amount of rows affected/found)
num_rows = cursor.execute(query)
# Work with the results
# Close the connection
db.close()
If you do a SELECT-query, you can either retrieve one row or loop through all of them. Here’s an example of both:
# Fetch only one row (mostly used for e.g. "SELECT COUNT(*)")
data = cursor.fetchone()
# Loop through all rows
data = cursor.fetchall()
for row in data:
# ...
All rows are represented as an array, without keys:
['First column', 'Another column', 'Etc...']