2

I wonder if it is possible to get the database name after a connection. I known that it is possible with the engine created by the function 'create_engine' (here) and I would like to have the same possibility after a connection.

from sqlalchemy import create_engine, inspect
engine = create_engine('mysql+mysqldb://login:pass@localhost/MyDatabase')
print (engine.url.database) # print the dabase name with an engine
con = engine.connect() 

I looked at the inspector tool, but there is no way to retrieve the database name like:

db_name = inspect(con.get_database_name() )

May be it is not possible. Any idea ?

Thanks a lot!

2 Answers 2

0

For MySQL, executing select DATABASE() as name_of_current_database should be sufficient. For SQL Server, it would be select DB_NAME() as name_of_current_database. I do not know of any inherently portable way of doing this that will work irrespective of the backend.

Sign up to request clarification or add additional context in comments.

Comments

0

I'm not sure if you found the answer to this yet but the way that I solved this issue was to reference the engine object from the connection. Based on the code that you had above, here's an example of what I did:

...
con = engine.connect() 

#reference the database engine from the connection object
db_name = con.engine.url.database

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.