More general way of generating PyODBC queries as a dict?

  • Thread starter stackoverflowuser95
  • Start date
S

stackoverflowuser95

Here are my averagely general class methods for creating a dictionary from the result of database queries:

def make_schema_dict(self):
schema = [i[2] for i in self.cursor.tables()
if i[2].startswith('tbl_') or i[2].startswith('vw_')]

self.schema = {table: {'scheme': [row.column_name for row
in self.cursor.columns(table)]}
for table in schema}

def last_table_query_as_dict(self, table):
return {'data': [{col: row.__getattribute__(col) for col in self.schema
['scheme']
if col != 'RowNum'} for row in self.cursor.fetchall()]}
Unfortunately as you can see, there are many complications.

For example, when multiple tables are queried; some hackish lambdas are required to generate the resulting dictionary.

Can you think of some more general methods?

(and yes I know this is against the PEP; and that this is also on SO)
 
D

Dennis Lee Bieber

For example, when multiple tables are queried; some hackish lambdas are required to generate the resulting dictionary.

Can you think of some more general methods?
What about using the information from

cursor.description

You did state PyODBC, did you not?

"""
description

This read-only attribute is a list of 7-item tuples, each containing
(name, type_code, display_size, internal_size, precision, scale,
null_ok). pyodbc only provides values for name, type_code,
internal_size, and null_ok. The other values are set to None.
"""
 
S

stackoverflowuser95

What about using the information from



cursor.description



You did state PyODBC, did you not?



"""

description



This read-only attribute is a list of 7-item tuples, each containing

(name, type_code, display_size, internal_size, precision, scale,

null_ok). pyodbc only provides values for name, type_code,

internal_size, and null_ok. The other values are set to None.

"""

--

Wulfraed Dennis Lee Bieber AF6VN

(e-mail address removed) HTTP://wlfraed.home.netcom.com/

YAY: `[{c[0]: v for (c, v) in zip(row.cursor_description, row)} for row in self.cursor.fetchall()]`
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top