Dr. John A Zoidberg Dr. John A Zoidberg - 1 year ago 68
Python Question

How can I get column name and type from an existing table in SQLAlchemy?

Suppose I have the table

and I want to know what the column names are and what the types are for each column.

I connect like this;

connectstring = ('mssql+pyodbc:///?odbc_connect=DRIVER%3D%7BSQL'

engine = sqlalchemy.create_engine(connectstring).connect()
md = sqlalchemy.MetaData()
table = sqlalchemy.Table('users', md, autoload=True, autoload_with=engine)
columns = table.c

If I call

for c in columns:
print type(columns)

I get the output

<class 'sqlalchemy.sql.base.ImmutableColumnCollection'>

printed once for each column in the table.

print columns


['users.column_name_1', 'users.column_name_2', 'users.column_name_3'....]

Is it possible to get the column names without the table name being included?

Answer Source

columns have name and type attributes

for c in columns:
    print c.name, c.type