Unpacking of query result

Fredrik Lundh fredrik at pythonware.com
Sun Apr 30 05:00:41 EDT 2006


"DarkBlue" <nomail at nixmail.com> wrote:

> Following part of an database query works fine :
>
> self.cur=con1.cursor
> self.cur.execute('select a,b,c,d from t1')
> for (a,b,c,d) in self.cur:
>     print a,b,c,d
>
>
> but how to do this:
>
> self.cur.execute(sql_select_text_put_in_at_runtime)
> for (whatever_was_in_the_select_text_part_of_the_query) in self.cur:
>     print 'returned result set'
>
> Will it be necessary to parse the sql string and find any possible
> return columns or is there a better way so that the query can be used
> generically , that is without knowing at coding time
> what or how many columns will be returned ?

reading the DB-API documentation might help:

    http://www.python.org/dev/peps/pep-0249/

    /.../

    Cursor Objects should respond to the following methods and
    attributes:

        .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.

            This attribute will be None for operations that
            do not return rows or if the cursor has not had an
            operation invoked via the executeXXX() method yet.

            The type_code can be interpreted by comparing it to the
            Type Objects specified in the section below.

    /.../

</F>






More information about the Python-list mailing list