alphanumeric
alphanumeric

Reputation: 19329

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:[email protected]')
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?

Upvotes: 29

Views: 31798

Answers (2)

balu mahendran
balu mahendran

Reputation: 129

SQLAlchemyError class gives many details about the error. One such is __cause__ which gives short reason why the error happened (like password not correct or server name not correct)

from sqlalchemy import create_engine
from sqlalchemy.exc import SQLAlchemyError
engine = create_engine(
    "postgresql+psycopg2://user_name:pass_word@localhost/db_name")
try:
    engine.connect()
    print("success")
except SQLAlchemyError as err:
    print("error", err.__cause__)  # this will give what kind of error

Upvotes: 8

Stephen Rauch
Stephen Rauch

Reputation: 49784

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:[email protected]')
engine.connect()

Will raise the error:

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

Upvotes: 49

Related Questions