[Zope] Getting SQL record names in python script?

Chris Kratz chris.kratz@vistashare.com
Tue, 13 Nov 2001 11:09:04 -0500


Not sure if anyone responded to this or not, but once you have the
recordset, you can get the column names by using the .names() function.
Here is some code that should create a table with any arbitrary select.

records = select()   # run the select ZSQL statement and put rows into
records var
headings = records.names()  # Extract a list of heading names in order
received from DB

# Start HTML Table and begin row
print '<table><tr>'

# Print headings
for heading in headings:
   print '<th>'+heading+'</th>'

print '</tr>'  # End row

# Print table data
for record in records: # Iterate through the records
   print '<tr>'
   for heading in headings:   # Iterate through the columns within row
      print '<td>'
      print record[heading]   #  Get the data value by column name
      print '</td>'
   print '</tr>'

# Close Table
print '</table>'

# return result to caller
return printed

Then a simple <dtml-var pythonScriptName> will display the table in a DTML
method or doc.

I got so tired of building the same table code over and over again that I
created a much more complex version of this that takes any sql statement and
builds an HTML table that allows displaying x rows with begin and next links
as well as allows arbitrary sorting by column headings.  And since we do a
lot of maintenance of database tables, it also has hooks for adding a row,
dropping a row, changing a row and validating a row.  So building a
particular page is much simpler now.  It standardized our tables and reduced
the number of errors greatly at the expense of some speed.  Once the design
has quieted down some, I may look at implementing part of it in C in an
external method to enhance performance.

Hope that helps,

-chris
------------------------------
Chris Kratz
chris.kratz@vistashare.com

----- Original Message -----
From: <azbok@yahoo.com>
To: <zope@zope.org>
Sent: Monday, November 12, 2001 6:57 PM
Subject: [Zope] Getting SQL record names in python script?


> I call a ZSQL method in python and successfully retrieve the results I
> want.  Then I want to get a list of the field names.
>
> I try
>   MyRec = context.GetRecord()
>   print MyRec[0].keys()
>
> I get
>   Error Type: AttributeError
>   Error Value: keys
>
> I can cycle through the values no problem.  I thought the records
> returned were each a dictionary.  Is keys one of those functions that
> is restricted?
>
> How would I get field names?
>
> Thank you very much
>
>
>
> _______________________________________________
> Zope maillist  -  Zope@zope.org
> http://lists.zope.org/mailman/listinfo/zope
> **   No cross posts or HTML encoding!  **
> (Related lists -
>  http://lists.zope.org/mailman/listinfo/zope-announce
>  http://lists.zope.org/mailman/listinfo/zope-dev )
>