from sqlalchemy import inspect
inspector = inspect(engine)
schemas = inspector.get_schema_names()
for schema in schemas:
print("schema: %s" % schema)
for table_name in inspector.get_table_names(schema=schema):
for column in inspector.get_columns(table_name, schema=schema):
print("Column: %s" % column)
from sqlalchemy import create_engine
from sqlalchemy import inspect
engine = create_engine('...')
insp = inspect(engine)
print(insp.get_table_names())
旧方法(engine.table_names())收益率:
SADeprecationWarning: The from_engine() method on Inspector is deprecated and will be removed in a future release. Please use the sqlalchemy.inspect() function on an Engine or Connection in order to acquire an Inspector. (deprecated since: 1.4)
from sqlalchemy import create_engine, inspect
from sqlalchemy_utils.functions import database_exists, create_database
engine = create_engine('sqlite:///mydb.sqlite', echo=True)
if not database_exists(engine.url):
create_database(engine.url)
else:
engine.connect()
df.to_sql('MyTable', con=engine, if_exists='replace', index=False) # index=False avoids auto-creation of level_0 (name tiebreaker)
inspector = inspect(engine)
table_names = inspector.get_table_names()
for table_name in table_names:
print(f"Table:{table_name}")
column_items = inspector.get_columns(table_name)
print('\t'.join(n for n in column_items[0]))
for c in column_items:
assert len(c) == len(column_items[0])
print('\t'.join(str(c[n]) for n in c))