26

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?

alphanumeric
  • 17,967
  • 64
  • 244
  • 392

2 Answers2

47

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)")
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
5

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
balu mahendran
  • 119
  • 1
  • 4
  • This answer doesn't provide an detail as to why the code you've written will work. Please add details allowing the asker to understand what you've done and why. – HPringles Nov 30 '21 at 10:02