MySQL Access with Python

This is a rough outline of the series of commands necessary to connect, query and display rows in a table.

Connect & Database Selection

try: 
  import MySQLdb
  connection = MySQLdb.connect(host="mysql.aero.und.edu", user="rfillion", passwd="password-goes-here", db="rfillion" )
except:
  print "Could not connect to database."
  import sys
  sys.exit(0)

Obtaining a cursor

cursor = connection.cursor(MySQLdb.cursors.DictCursor)

Query

query = 'select * from notes'
cursor.execute(query)

Display Results

for line in cursor.fetchall():
  id = line['id']
  date = line['date']
  content = line['content']
  print "ID: %i, DATE: %s, CONTENT: %s<br/>" % (id, date, content)

Better Display of Results

for line in cursor.fetchall():
  print "ID: %(id)i, DATE: %(date)s, CONTENT: %(content)s<br/>" % line

Additional Reading


resource/mysql/python.txt · Last modified: 2007/07/26 12:00 by akuelbs