Skip to content Skip to sidebar Skip to footer

How To Get Column Names Of A Schema In Sqlsoup In Python?

How do you get column names and types in a dictionary from a schema/table using SQLSOUP in python? With MySQLDB I can create a cursor and use cursor.description. is there some equi

Solution 1:

According to the documentation:

A Table object can be instructed to load information about itself from the corresponding database schema object already existing within the database. This process is called reflection. In the most simple case you need only specify the table name, a MetaData object, and the autoload=True flag. If the MetaData is not persistently bound, also add the autoload_with argument:

>>> messages = Table('messages', meta, autoload=True, autoload_with=engine)
>>> [c.name for c in messages.columns]
['message_id', 'message_name', 'date']

Solution 2:

It appears that sqlsoup does have the ability to tell you the column names and types directly without going "underneath" to sqlalchemy. Table objects in sqlsoup have a member collection called 'c' that contains all the columns of the table, like so:

>>> import sqlsoup
>>> db =sqlsoup.SQLSoup('sqlite:///test.sqlite')
>>> db.example_table.c
<sqlalchemy.sql.expression.ColumnCollection object at 0x1059819d0>
>>> db.example_table.c.keys()
[u'column_1', u'column_2', u'column_3']
>>> db.example_table.c['column_1']
Column(u'column_1', VARCHAR(), table=<example_table>, primary_key=True, nullable=False)
>>> db.example_table.c['column_1'].type
VARCHAR()

Post a Comment for "How To Get Column Names Of A Schema In Sqlsoup In Python?"