Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List database tables with SQLAlchemy

I want to implement a function that gives information about all the tables (and their column names) that are present in a database (not only those created with SQLAlchemy). While reading the documentation it seems to me that this is done via reflection but I didn't manage to get something working. Any suggestions or examples on how to do this?

like image 514
drgxfs Avatar asked Jan 23 '14 14:01

drgxfs


People also ask

What does DB Create_all () do?

create_all() function to create the tables that are associated with your models. In this case you only have one model, which means that the function call will only create one table in your database: from app import db, Student. db.

What is SQLAlchemy table?

The SQL Expression Language constructs its expressions against table columns. SQLAlchemy Column object represents a column in a database table which is in turn represented by a Tableobject. Metadata contains definitions of tables and associated objects such as index, view, triggers, etc.

How do I get column names in SQLAlchemy?

To access the column names we can use the method keys() on the result. It returns a list of column names. Since, we queried only three columns, we can view the same columns on the output as well.


1 Answers

start with an engine:

from sqlalchemy import create_engine engine = create_engine("postgresql://u:p@host/database") 

quick path to all table /column names, use an inspector:

from sqlalchemy import inspect inspector = inspect(engine)  for table_name in inspector.get_table_names():    for column in inspector.get_columns(table_name):        print("Column: %s" % column['name']) 

docs: http://docs.sqlalchemy.org/en/rel_0_9/core/reflection.html?highlight=inspector#fine-grained-reflection-with-inspector

alternatively, use MetaData / Tables:

from sqlalchemy import MetaData m = MetaData() m.reflect(engine) for table in m.tables.values():     print(table.name)     for column in table.c:         print(column.name) 

docs: http://docs.sqlalchemy.org/en/rel_0_9/core/reflection.html#reflecting-all-tables-at-once

like image 155
zzzeek Avatar answered Oct 08 '22 23:10

zzzeek