我可以使用无效的用户名、密码或地址声明 engine
对象,并且不会出现异常或错误:
from sqlalchemy import create_engine
engine = create_engine('mysql://nouser:nopassword@123.456.789')
print engine
它打印喜欢它是一个有效的引擎对象:
Engine(mysql://nouser:***@123.456.789)
验证(检查)
engine
对象是否有效或它是否“可连接”到数据库的常用方法是什么?
最佳答案
问题:如何验证引擎对象是否“可连接”?
从( 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.
因此,要测试引擎对象是否“可连接”,需要显式调用
Engine.connect()
或尝试以其他方式使用引擎。from sqlalchemy import create_engine
engine = create_engine('mysql://nouser:nopassword@123.456.789')
engine.connect()
会引发错误:
sqlalchemy.exc.OperationalError: (_mysql_exceptions.OperationalError) (2005, "Unknown MySQL server host '123.456.789' (0)")
关于python - 如何验证 SqlAlchemy 引擎对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41887344/