18

Is it possible to get a list of all databases in SQLAlchemy? I need a cross-database solution, so basic "SHOW DATABASES" doesn't cut it.

Similar to MetaData/Inspector capabilities to show all tables and columns.

3 Answers 3

26

Looks like I found the answer myself.

There is a method called get_schema_names in Inspector class, which is not very well documented, but returns list of databases (just tested with MySQL and Postgres).

Usage:

import sqlalchemy as sa
engine = sa.create_engine('mysql+pymysql://user:pwd@localhost')
insp = sa.inspect(engine)
db_list = insp.get_schema_names()
print(db_list)
4
  • 14
    Maybe I'm missing something - but this doesn't return a list of databases. It just returns the list of schemas on a single database. I'm using PostgreSQL 9.5.
    – Guy
    Aug 1, 2016 at 11:21
  • Coud you tell us which version of mysql are you using?
    – ras212
    Apr 8, 2018 at 18:17
  • It is working with MySQL but not PostgreSQL whenever I am using this connection string postgresql://user:pwd@localhost May 26, 2020 at 4:46
  • To echo @Guy, this returns a list of schemas, not databases. I think OP has mixed up their labeling of schemas vs databases. May 20, 2021 at 1:32
4
engine.execute('SELECT datname FROM pg_database;').fetchall()

Every entity in DB is saved in some "system" table. For example, in Postgres you can get all DBs from pg_database table.

2
  • 1
    Please put your answer always in context instead of just pasting code. See here for more details. May 14, 2020 at 12:52
  • While this code may resolve the OP's issue, it is best to include an explanation as to how your code addresses the OP's issue. In this way, future visitors can learn from your post, and apply it to their own code. SO is not a coding service, but a resource for knowledge. Also, high quality, complete answers are more likely to be upvoted. These features, along with the requirement that all posts are self-contained, are some of the strengths of SO as a platform, that differentiates it from forums. You can edit to add additional info &/or to supplement your explanations with source documentation. May 15, 2020 at 0:29
-1

Here is a solution i came up with for mysql:

    from sqlalchemy import create_engine
    eng = create_engine('mysql+pymysql://root:password@localhost:3306', pool_recycle=3600)
    q = eng.execute('SHOW DATABASES')
    available_tables = q.fetchall()

It does an execute and returns all of the rows.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.