gpt4 book ai didi

python - 如何捕获 SQLAlchemy 上的特定数据库错误

转载 作者:太空宇宙 更新时间:2023-11-03 18:40:49 25 4
gpt4 key购买 nike

我想询问有关SQLAlchemy中的引擎的问题。

这是我的代码:

try:
engine = create_engine('postgres://postgres:pass@localhost:5432/db')
engine.connect()
except DatabaseError:
print('Database Error : ', sys.exc_info()[1])

如何捕获特定错误的异常,例如“数据库不存在”或“密码/用户名错误”等

最佳答案

Python DBAPI 对于这些事情没有特定的异常(exception),因此您能做的最好的事情就是解析字符串:

try:
# code
except DatabaseError, e:
if "database does not exist" in str(e):
# do something

关于python - 如何捕获 SQLAlchemy 上的特定数据库错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20545487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com