psycopg2 or pygresql?

Steve Holden steve at holdenweb.com
Wed Sep 19 11:47:38 EDT 2007


exhuma.twn wrote:
> Plain and simple. What would you use?
> 
> So far I have written everything with psycopg2. One thing that annoys
> me is that I cannot easily access the column names from a query. I
> know that this is not part of the DBAPI2  so I cannot expect the model
> to suport it.
> 
Yes it is.

Execute a SELECT * FROM TABLE WHERE 1=0 and then examine 
cursor.description. This allows you to introspect on database structure.

> I quite like the "mogrify" method of psycopg2 very much. It's very
> useful for debugging.
> 
> And before someone says: "Use the DictCursor-factory to access column
> names". Yes I can do that. But a dict does not guarantee the same
> order of keys as the columns were specified in the query.
> 
See below.

> The reason: I wrote a very simple Qt-Widget (inherited from
> QTableWidget) that takes a SQL query and displays the results. And I
> would like to have the columns ordered the same way as I specified in
> the query *with* a header-label. For now I hava a method on the widget
> which takes a query, *and* a list of labels.
> 
> I can live with that though. Although it itches me.
> 
> Would pygresql solve my dilemma? Or would you rather say: "Don't use
> pygresql!"  ;)
> 
Here's a psycopg2-based session:

 >>> curs
<cursor object at 0x00B823C8; closed: 0>
 >>> curs.execute("SELECT * FROM Person WHERE 1=0")
 >>> curs.description
(('psnid', 23, None, 4, None, None, None), ('psnfirstname', 1043, None, 
50, None, None, None), ('psnlastname', 1043, None, 50, None, None, 
None), ('psndear', 1043, None, 50, None, None, None), ('psntitle', 1043, 
None, 50, None, None, None), ('psnworkphone', 1043, None, 30, None, 
None, None), ('psnworkextension', 1043, None, 20, None, None, None), 
('psnhomephone', 1043, None, 30, None, None, None), ('psnmobilephone', 
1043, None, 30, None, None, None), ('psnfaxnumber', 1043, None, 30, 
None, None, None), ('psnemailname', 1043, None, 50, None, None, None), 
('psnreferredby', 1043, None, 50, None, None, None), ('psnlocid', 23, 
None, 4, None, None, None), ('psnnotes', 1043, None, -1, None, None, None))

I believe if you use specific column names in your query they will 
appear in the order given in the query also.

I use this technique in

   http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81189

to print arbitrary query outputs.

regards
  Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd           http://www.holdenweb.com
Skype: holdenweb      http://del.icio.us/steve.holden

Sorry, the dog ate my .sigline




More information about the Python-list mailing list