473,811 Members | 2,981 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

DB-API: how can I find the column names in a cursor?

A.M
Hi

I use a code similar to this to retrieve data from Oracle database:

import cx_Oracle

con = cx_Oracle.conne ct("me/secret@tns")

cur = con.cursor()

outcur = con.cursor()

cur.execute("""

BEGIN

MyPkg.MyProc(:c ur);

END;""", cur=outcur)

for row in out_cur:

print row

The problem is I don't know how to find out what are the column name and
type that comes out of query (each row in cursor).

Is there any possibility that my Python code can find out the column name
and type in each row in cursor?

The other problem is accessing data in each row by column name. In Ruby I
can say:

Print row["ColName"]

In Python; however, I must access to row contents by integer index, like
PRINT ROW[0], which reduces my program's readability.

Can I access to row's contents by column name?

Any help would be appreciated,

Alan
Jun 1 '06 #1
6 17486
"A.M" wrote:
The problem is I don't know how to find out what are the column name and type that comes out of
query (each row in cursor).

Is there any possibility that my Python code can find out the column name and type in each row in
cursor? From "cursor objects" in the DB-API documentation:


.description

"This read-only attribute is a sequence of 7-item
sequences. Each of these sequences contains information
describing one result column: (name, type_code,
display_size, internal_size, precision, scale,
null_ok). The first two items (name and type_code) are
mandatory, the other five are optional and must be set to
None if meaningfull values are not provided."

The full spec is available here: http://www.python.org/dev/peps/pep-0249/

</F>

Jun 1 '06 #2
A.M
Thank you Fredrik for help.

Would you be able to help with the second part of question:

The other problem is accessing data in each row by column name. In Ruby I
can say:

Print row["ColName"]

In Python; however, I must access to row contents by integer index, like
PRINT ROW[0], which reduces my program's readability.

Can I access to row's contents by column name?

Thanks again,
Alan

"Fredrik Lundh" <fr*****@python ware.com> wrote in message
news:ma******** *************** *************** *@python.org...
"A.M" wrote:
The problem is I don't know how to find out what are the column name and
type that comes out of query (each row in cursor).

Is there any possibility that my Python code can find out the column name
and type in each row in cursor?

From "cursor objects" in the DB-API documentation:


.description

"This read-only attribute is a sequence of 7-item
sequences. Each of these sequences contains information
describing one result column: (name, type_code,
display_size, internal_size, precision, scale,
null_ok). The first two items (name and type_code) are
mandatory, the other five are optional and must be set to
None if meaningfull values are not provided."

The full spec is available here: http://www.python.org/dev/peps/pep-0249/

</F>

Jun 1 '06 #3
I don't know if it works this way with Oracle, but the python dbpai has
the cursor.descript ion method that can help. For example:

cur.execute( "your query here" )
columns = [i[0] for i in cur.description]

cur.description gives a lot of data about your recordset, and the first
field is the column name.

Hope this helps...
Luis
A.M wrote:
Hi

I use a code similar to this to retrieve data from Oracle database:

import cx_Oracle

con = cx_Oracle.conne ct("me/secret@tns")

cur = con.cursor()

outcur = con.cursor()

cur.execute("""

BEGIN

MyPkg.MyProc(:c ur);

END;""", cur=outcur)

for row in out_cur:

print row

The problem is I don't know how to find out what are the column name and
type that comes out of query (each row in cursor).

Is there any possibility that my Python code can find out the column name
and type in each row in cursor?

The other problem is accessing data in each row by column name. In Ruby I
can say:

Print row["ColName"]

In Python; however, I must access to row contents by integer index, like
PRINT ROW[0], which reduces my program's readability.

Can I access to row's contents by column name?

Any help would be appreciated,

Alan


Jun 1 '06 #4
A.M wrote:
for row in out_cur:

print row
[...]

The other problem is accessing data in each row by column name.


One useful technique is
for col1, col2, col3 in out_cur:
sum = sum + col3

Access is still by index, but your code uses ordinary Python variables.
It works better with SELECTs as you can choose the output columns in the
SQL. With stored procedures, there's always the possibility of someone
changing the structure of the result set.

There exists a general library for your solution:
http://opensource.theopalgroup.com/

Daniel
Jun 1 '06 #5
A.M <al******@newsg roup.nospam> wrote:
The other problem is accessing data in each row by column name. In Ruby I
can say:

Print row["ColName"]

In Python; however, I must access to row contents by integer index, like
PRINT ROW[0], which reduces my program's readability.

Can I access to row's contents by column name?


columns = dict((name, col) for col, name in enumerate(curso r.description))
print row[columns["ColName"]]

And please don't top-post.

--
\S -- si***@chiark.gr eenend.org.uk -- http://www.chaos.org.uk/~sion/
___ | "Frankly I have no feelings towards penguins one way or the other"
\X/ | -- Arthur C. Clarke
her nu becomež se bera eadward ofdun hlęddre heafdes bęce bump bump bump
Jun 1 '06 #6
Alan> The other problem is accessing data in each row by column name. In
Alan> Ruby I can say:

Alan> Print row["ColName"]

Alan> In Python; however, I must access to row contents by integer
Alan> index, like PRINT ROW[0], which reduces my program's readability.

Alan> Can I access to row's contents by column name?

There are a couple things you can try. First, see if the adaptor for your
database has a way to specify that query results should be returned as a
list of dicts instead of a list of tuples. MySQLdb allows you to select the
style of cursor class to instantiate when you create the connection. I
think Psycopg provides a dictcursor() method on the connection (though I may
be misremembering - it's been awhile). Other adaptors may provide similar
functionality.

Failing that, you can whip something up yourself using the description
attribute to which Fredrik referred:

for row in curs.fetchall() :
row = dict(zip([d[0] for d in curs.descriptio n], row))
...

Skip
Jun 1 '06 #7

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

Similar topics

2
2565
by: Oliver Peek | last post by:
Hi all, Probably my fault, I'm opening a Berkeley DB file, iterating through and deleting keys, well making an attempt. I get this error when I try to delete. ---error Traceback (most recent call last): File "./db.py", line 41, in ?
22
5598
by: Smutny30 | last post by:
Hello, I am preparing a database that will store 10 n * GBs - 100 n * GBs of data. I calculated to have 1,2 GB of bufferpools. I run the DB2 v. 8.2.1 alone on 4 GB box. I obtain : "SQL1478W The defined buffer pools could not be started. Instead, one small
2
2471
by: Greg Strong | last post by:
Hello All, I've written code in a test database with test data. Everything seems to be working except compact database in VB code per http://www.mvps.org/access/general/gen0041.htm. The reason I say this is the auto number fields are NOT being reset to zero. I delete the data from tables with action delete queries, then call the compact DB code which is followed by importing data to tables and subsequent append queries to other tables....
2
2202
by: Sam Shaw | last post by:
I have been looking after an MS Access database, using table links to access data in a back-end MDB database. We have recently micrated to a SQL Server 2000 back-end atabase, once again accessing it though table links. I am comfortable with the data side of things (whether through table links or an adodb.recordset). What I am missing, however, is all the useful things you could do to automatically maintain a back-end database from a...
2
2071
by: daralthus | last post by:
Hello! I would like to ask your help, i have founded a great code here: http://www.jamescaws.co.uk/2008/07/dynamically-count-exit-link-clicks-throughs-using-javascript-php/ but it uses Pear DB for the database connection. the problem is that it don't works, actually the php don't writes anything in the table and i don't get any error when i add the if (PEAR::isError($db)) { die($db->getMessage());} code, so not the connection... Then i...
0
9607
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
10653
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...
0
10395
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10408
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,...
1
7674
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6895
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5564
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...
1
4352
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
3876
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.