473,804 Members | 2,117 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

module for working with the result set

Hi,
newbie question:
PyPgSQL (postgres driver) returns a list (not a tuple O'Rielly states
DBAPI returns a tuple) and most of the books describe how to work with
tuples and dictionaries when working with a result set. Does anyone know
of a paper or tutorial that explains a few ways to deal with result
sets. Or if anyone knows of a module that will help (that I can study) -
that would be just as helpful?

TIA
John
Jul 18 '05
15 1680
john fabiani writes:
following your thoughts on the keys and my mistake - can you
tell me how to get into a dict format?


For MySQL, there is the DictCursor class. Here's an example,
and you should even be able to use it as-is as I've opened up
public access to my MySQL database:
import MySQLdb.cursors
conn = MySQLdb.connect (host='melder.p aulmcnett.com', user='dabo', passwd='dabo', db='dabotest')
dictCursor = conn.cursor(cur sorclass=MySQLd b.cursors.DictC ursor)
print dictCursor.exec ute('select * from recipes where mingred like "%coriander %"') 14 recordSet = dictCursor.fetc hall()
for record in recordSet:

.... print record['iid'], record['ctitle']
....
184 Cucumber Salad
186 Garlic Shrimps
193 Chinese Salad with Crispy Won Tons
299 Chicken Curry
304 Kai Phat Khing
305 Kung Tom Yam
306 Ma Ho
308 Yam Krachup
332 Lentil Soup
817 Mixed Vegetable Curry
841 Thai Mushroom Soup
843 Rice Noodle Salad with Ginger
915 Santa Fe Stew
966 Mixed Potato Soup
--
Paul
http://www.paulmcnett.com

Jul 18 '05 #11
Paul McNett wrote:
john fabiani writes:

following your thoughts on the keys and my mistake - can you
tell me how to get into a dict format?

For MySQL, there is the DictCursor class. Here's an example,
and you should even be able to use it as-is as I've opened up
public access to my MySQL database:

import MySQLdb.cursors
conn = MySQLdb.connect (host='melder.p aulmcnett.com', user='dabo', passwd='dabo', db='dabotest')
dictCurso r = conn.cursor(cur sorclass=MySQLd b.cursors.DictC ursor)
print dictCursor.exec ute('select * from recipes where mingred like "%coriander %"')
14
recordSet = dictCursor.fetc hall()
for record in recordSet:


... print record['iid'], record['ctitle']
...
184 Cucumber Salad
186 Garlic Shrimps
193 Chinese Salad with Crispy Won Tons
299 Chicken Curry
304 Kai Phat Khing
305 Kung Tom Yam
306 Ma Ho
308 Yam Krachup
332 Lentil Soup
817 Mixed Vegetable Curry
841 Thai Mushroom Soup
843 Rice Noodle Salad with Ginger
915 Santa Fe Stew
966 Mixed Potato Soup

I know about the MySQL Dictcusor but I'm using Postgres. I'm not
married to Postgres but I had excellent success with it along with a VFP
front end.
BTW is the MySQL Dictclass writen in "C" (part of the driver) or a
python class/module? Maybe I can copy the code if it's python.
thanks
John
Jul 18 '05 #12
john fabiani writes:
I know about the MySQL Dictcusor but I'm using Postgres. I'm
not married to Postgres but I had excellent success with it
along with a VFP front end.
Oops I thought it was you that was using MySQL, sorry my bad. I
had some code lying around that would generate a dictcursor
generically - check on ASPN in the Python Cookbook and search
for 'lazy db'.
BTW is the MySQL Dictclass writen in "C" (part of the driver)
or a python class/module? Maybe I can copy the code if it's
python. thanks


IIRC it is pure Python.

--
Paul
http://www.paulmcnett.com

Jul 18 '05 #13
> OK thats great! I did the following and it works.
for field in range(0,len(myd ata[0])):
print mydata[0][field]
following your thoughts on the keys and my mistake - can you tell me how
to get into a dict format?


Its a one-liner: If fnames is the list of column names (remember you can get
these from the cursor) and row is your data, this will create a dict out of
them:

d = dict(zip(fnames , row))

Thats all.
--
Regards,

Diez B. Roggisch
Jul 18 '05 #14
Diez B. Roggisch wrote:
OK thats great! I did the following and it works.
for field in range(0,len(myd ata[0])):
print mydata[0][field]
following your thoughts on the keys and my mistake - can you tell me how
to get into a dict format?

Its a one-liner: If fnames is the list of column names (remember you can get
these from the cursor) and row is your data, this will create a dict out of
them:

d = dict(zip(fnames , row))

Thats all.

I'm missing something very important about list and dict because your
one liner does not work. This is what I did:

myfields=mycur. description
#since I already had the data I used it.
d = dict(zip(myfiel ds,mydata[0]))
Traceback (most recent call last):
File "<input>", line 1, in ?
TypeError: list objects are unhashable
So "myfields" is a list within a list.
I'm able to list the fields with the following:
for count in range(0,len(myf ields)):
print myfields[count][0]

The above will print the fields name - which is what I want to become my
keys. So now I have to make what is printed into a list.

mylist=[]
for count in range(0,len(myf ields)):
mylist.append(m yfields[count][0])
now I have a single list.
['csono', 'crevision',... .........]

then I'd expect your code to work but I get a list of tuples
[('csono', '5992 '), ('crevision', 'A') ......]

What I expected to see was
{'csono': '5992 '...}

So now I'm completely confused.... But I guess I'm learning....
John
Jul 18 '05 #15
> myfields=mycur. description
#since I already had the data I used it.
d = dict(zip(myfiel ds,mydata[0]))
Traceback (most recent call last):
File "<input>", line 1, in ?
TypeError: list objects are unhashable
ah, I forgot that the description contains more than the name. But I see you
figured that out yourself.

then I'd expect your code to work but I get a list of tuples
[('csono', '5992 '), ('crevision', 'A') ......] What I expected to see was
{'csono': '5992 '...}


You most probably forgot the dict around the zip, as this works:
dict([('csono', '5992 '), ('crevision', 'A')])

{'csono': '5992 ', 'crevision': 'A'}
The builtin dict takes a list of tuples and makes them a dictinairy with
keys from the first element of the tuple and values from the second.

--
Regards,

Diez B. Roggisch
Jul 18 '05 #16

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2603
by: Peter Åstrand | last post by:
There's a new PEP available: PEP 324: popen5 - New POSIX process module A copy is included below. Comments are appreciated. ---- PEP: 324 Title: popen5 - New POSIX process module
2
1996
by: James S | last post by:
Hi, Basically I've been fighting with this code for a few days now and can't seem to work around this problem. Included is the output, the program I use to get this error and the source code for my wrapper. This is acually part of the project, libxmlconf on sourceforge. The newest working version isn't there yet, and cvs is lagged by 6 hours or so. So if you think you want to have a try at this I can tgz the source for you. My...
0
1363
by: Jeff | last post by:
Ok, so I'm working on a project right now that is being done in psp through apache. This is working fine, except that in every one of my modules I had to use the mod_python function of apache.import_module for its autoreload capability. Now I cannot open or run any of my classes in the interpreter without getting a "No module named _apache" error. I need to get this working, as I am without unittesting right now. I also tried making...
1
4187
by: Kenneth McDonald | last post by:
I'm working on the 0.8 release of my 'rex' module, and would appreciate feedback, suggestions, and criticism as I work towards finalizing the API and feature sets. rex is a module intended to make regular expressions easier to create and use (and in my experience as a regular expression user, it makes them MUCH easier to create and use.) I'm still working on formal documentation, and in any case, such documentation isn't necessarily the...
0
1232
by: Dave Cole | last post by:
WHAT IS IT: The Sybase module provides a Python interface to the Sybase relational database system. It supports all of the Python Database API, version 2.0 with extensions. NOTES: This release contains a number of small bugfixes and patches received from users.
0
1315
by: Dave Cole | last post by:
WHAT IS IT: The Sybase module provides a Python interface to the Sybase relational database system. It supports all of the Python Database API, version 2.0 with extensions. NOTES: This release contains a number of small bugfixes and patches received from users.
0
1200
by: Dave Cole | last post by:
WHAT IS IT: The Sybase module provides a Python interface to the Sybase relational database system. It supports all of the Python Database API, version 2.0 with extensions. NOTES: The 0.37 release is identical to 0.37pre3 as no problems were reported with the prerelease.
2
2752
by: Mythran | last post by:
I'm trying to add a module template to a project programmatically. I've tried many documented (w/o examples) ways of doing it to no avail. For example, I tried using Project.ProjectItems.AddFromTemplate("C:\Program Files\Microsoft Visual Studio .NET 2003\Vb7\VBWizards\Module\Templates\1033\Module.vb", "Common.vb") and this adds it ok. Problem is, it does not replace the stays as such). So I tried the DTE.LaunchWizard method and passed...
1
17266
by: alain MONTMORY | last post by:
Hello everybody, I am a newbie to python so I hope I am at the right place to expose my problem..... :-http://www.python.org/doc/2.4.2/ext/pure-embedding.html 5.3 Pure Embedding I download the code example from http://www.python.org/doc/2.4.2/ext/run-func.txt I call the file "TestOfficiel.c" and I compile it with : gcc -g -I/usr/include/python2.3/ TestOfficiel.c -o TestOfficiel -lpython2.3 -ldl all is OK (or seems to be...).
0
9716
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9595
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10604
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10359
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10101
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5536
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5675
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4314
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3837
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.