How to verify SqlAlchemy engine object

ぃ、小莉子 提交于 2021-02-07 11:23:09

问题


I can declare engine object with the invalid username, password or address and get no exception or error:

from sqlalchemy import create_engine
engine = create_engine('mysql://nouser:nopassword@123.456.789')
print engine

it prints likes it is a valid engine object:

Engine(mysql://nouser:***@123.456.789)

What would be a common way to verify (to check) if the engine object is valid or if it is "connectable" to db?


回答1:


Question: How to verify if the engine object is "connectable"?

From the (DOCs):

Note that the Engine and its underlying Pool do not establish the first actual DBAPI connection until the Engine.connect() method is called, or an operation which is dependent on this method such as Engine.execute() is invoked. In this way, Engine and Pool can be said to have a lazy initialization behavior.

So, to test if the engine object is "connectable" one needs to either explicitly call Engine.connect(), or attempt to use the engine in some other way.

from sqlalchemy import create_engine
engine = create_engine('mysql://nouser:nopassword@123.456.789')
engine.connect()

Will raise the error:

sqlalchemy.exc.OperationalError: (_mysql_exceptions.OperationalError) (2005, "Unknown MySQL server host '123.456.789' (0)")


来源:https://stackoverflow.com/questions/41887344/how-to-verify-sqlalchemy-engine-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!