4544l2.txt

Listing 2.

#!/usr/bin/python

import cgi    # the cgi module handles the form data 
import MySQL  # the MySQL module connects to mysqld

# Get the HTML form data:
form = cgi.FieldStorage() # form is a dictionary with form-field:data pairs 
title = black = white = year = rez = ""

if form.has_key("title"):     
   title = form['title'].value

if form.has_key("black"):
   black = form['black'].value

if form.has_key("white"):
   white = form['white'].value

if form.has_key("year"):
   year = form['year'].value

if form.has_key("rez"):
   if form['rez'].value == "b":
      rez = "%B%"  # to prepare for mysql queries of type 
		   # '...where rez like "%B%"...'
   elif form['rez'].value == "w":
      rez = "%W%"

# Make a list of tables that will be queried:
tlist = [] 
if title=="Honinbo":
   tlist.append("hon")
elif title=="Gosei":
   tlist.append("gosei")
elif title=="Kisei":
   tlist.append("kisei")
elif title=="Meijin":
   tlist.append("meijin")
elif title=="Tengen":
   tlist.append("tengen")
elif title=="Judan":
   tlist.append("judan")
elif title=="all":
   tlist = ["hon", "gosei", "kisei", "meijin", "tengen", "judan"]

print "Content-type: text/html\n\n"

# The main loop that will query each table in tlist and print the result: 
for table in tlist:
   # Create the database query as a string:
   dbquery = 'select fname from ' + table + ' ' # only the SGF file name
   if black!="":
      dbquery = dbquery + 'where black = "' + black + '" '

   if white!="":
      if black=="":
         dbquery = dbquery + 'where white = " ' + white + '" ' 
      else:
         dbquery = dbquery + 'and white = " ' + white + '" ' 

   if year!="":
      if black=="" and white=="":
         dbquery = dbquery + 'where year(dt) = ' + year + ' '
      else:
         dbquery = dbquery + 'and year(dt) = ' + year + ' '

   if rez!="":
      if black=="" and white=="" and year=="":
         dbquery = dbquery + 'where rez like "' + rez + '"' 
      else:
         dbquery = dbquery + 'and rez like "' + rez + '"' 

   print "<h1> Query result for " + table + " </h1>"
   
   # Use MySQL module:
   DBH = MySQL.connect()    # DBH is a database handle
   DBH.selectdb('igo', 0)   # 0 means the query results are sent to the client 
   STH = DBH.query(dbquery) # STH contains the results of query 'dbquery'
   l = STH.fetchrows(-1)    # l is a list of row lists containing all the rows
   nr = STH.numrows()
   DBH.close()
   
   # process l and print HTML: 
   print '<p><ul>'
   for e in l: # e is the list of data in a row.
               # It contains only one item, the SGF file name.
      print '<li><a href="http://myhost' +\
            '/cgi-bin/getsgf.py?file=' + e[0] + '">'
      print e[0] + '</a>'
   
   print '</ul><p>'
   print `nr` + ' files' # reverse quotes make a string from an integer 
   print '<hr>'
   #end of main loop
