首页 > 解决方案 > SQLAlchemy:从连接中获取数据库名称

问题描述

我想知道是否可以在连接后获取数据库名称。我知道由函数'create_engine'(此处)创建的引擎是可能的,我希望在连接后也有同样的可能性。

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() 

我查看了检查器工具,但无法检索数据库名称,例如:

db_name = inspect(con.get_database_name() )

可能是不可能的。任何想法 ?

非常感谢!

标签: pythonsqlalchemy

解决方案


对于 MySQL,执行select DATABASE() as name_of_current_database应该就足够了。对于 SQL Server,它将是select DB_NAME() as name_of_current_database. 我不知道有任何固有的便携方式可以做到这一点,而不管后端如何。


推荐阅读