[Tutor] Python with MySQL ?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Jan 11 19:55:31 CET 2005



On Tue, 11 Jan 2005, Mark Kels wrote:

> How can I send SQL querys to a MySQL database with a python-CGI program ?

Hi Mark,


You'll want to grab a "Python DB API" module for MySQL.  The best one I've
seen for MySQL is 'MySQLdb':

    http://sourceforge.net/projects/mysql-python

and you should probably grab that for your system.  It should come with
some examples to help you get started.


Python.org has a section on Python's database support:

    http://www.python.org/topics/database/

with some documentation.  There used to be a tutorial linked from Linux
Journal there, but it's now restricted to subscribers!  *grrrr*



Here's an example program just to see how the pieces fit together:

###
import MySQLdb
connection = MySQLdb.connect(db="magic", user="dyoo",
                             password="abracadabra")
cursor = connection.cursor()
cursor.execute("""select name from cards where
                  tournament_type = 'restricted'""")
for (name,) in cursor.fetchall():
    print name
cursor.close()
connection.close()
###


I hope this helps you get started!



More information about the Tutor mailing list