A Short Python Example
Listing E.1 runs you through the basics of connecting, running queries, and processing results.Listing E.1: example.py
#!/usr/bin/env python
import MySQLdb
dbh = None
try:
dbh = MySQLdb.connect(user='guru2b', passwd='g00r002b',–
host='test.host.co.za', db='firstdb')
except:
print "Could not connect to MySQL server."
exit(0)
try:
cursor = dbh.cursor()
cursor.execute("UPDATE customer SET surname='Arendse' WHERE–
surname='Burger'")
print "Rows updated: ", cursor.rowcount
cursor.close()
except:
print "Could not update the table."
try:
cursor = dbh.cursor()
cursor.execute("SELECT first_name,surname FROM customer")
for row in cursor.fetchall():
print "Name: ", row[0], row[1]
dbh.close()
except:
print "Failed to perform query"
dbh.close()