Python and MySQL
A MySQL database can be queried from a python script with MySQLdb. Just download it here and install it, or if you are using FreeBSD it can be found under
/usr/ports/databases/py-MySQLdb.
In the python script import the MySQLdb module and declare a connection in cursor as in this example:
import MySQLdb
# Create a connection using your db info
db = MySQLdb.connect(host=”localhost”, user=”yourMysqlUser”, passwd=”youUserPass”,db=”yourDB”)
# Create a cursor, this can be used over and over
cursor = db.cursor()
# Build a query
q = “select user_id, user_name from users”
# run the query
cursor.execute(q)
# fetch the results
users = cursor.fetchall()
# loop through the results
for user in users:
print “ID %s Name: %s” % (user[0],user[1])
The cursor is created once from the connection and can be used for all queries in the script. The query selects two columns from the table and then script loops through them and prints them out. Each column is referenced by a number zero based as it comes back as a list. The order is set by the query.