Skip to content
Advertisement

How to verify SqlAlchemy engine object

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?

Advertisement

Answer

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)")
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement