异常处理:
# 异常一: AttributeError,对象属性不存在
with engine.connect() as conn:
trans = conn.begin()
s = select([users])
try:
r = conn.execute(s)
for record in r:
print record.Password
except AttributeError, e:
print 'found errors: {0}'.format(e)
trans.rollback()
# 异常二: IntegrityError,唯一约束错误
with engine.connect() as conn:
trans = conn.begin()
ins = users.insert().values(
id=2,
customer_number=2,
username='limanman',
email_address='xmdevops@vip.qq.com',
phone='11011011011',
password='2',
created_on='2016-11-06',
updated_on='2016-11-06',
)
from sqlalchemy.exc import IntegrityError
try:
res = conn.execute(ins)
print 'values: {0}'.format(res.inserted_primary_key)
except IntegrityError, e:
print 'found errors: {0}'.format(e)
trans.rollback()
说明: SQLAlchemy在运行中可能会抛出各种异常,但是最常见是AttributeError异常和IntegrityError异常,其实所有的异常类都可以在sqlalchemy.exc下面找到,通常我们会通过事务来防止异常数据的写入,当抛出异常时我们通过事务trans.rollback()回滚到trans = conn.begin()定义的事务开始位置.
反射技术:
1. 反射技术就是自动通过连接字符串加载已经存在的数据库,支持反射表/视图/索引/外键等,如反射还原表对象可以通过设置Table的autoload=True和autoload_with=engine实现
# 反射指定表
users = Table('users', metadata, autoload=True, autoload_with=engine)
print metadata.tables.keys()
print type(users), users, users.primary_key, dir(users)
# 反射整个库
metadata.reflect(bind=engine)
print metadata.tables.keys()
users = metadata.tables['users']
print type(users), users, users.primary_key, dir(users)
说明: 如上演示了常用于对已存在数据库/表/视图/索引自动加载,可通过Table(<tablename>, metadata, autoload=True, autoload_with=engine)来反射还原指定表对象,通过metadata.reflect(bind=engine)反射整个库,对已存在的数据库想切换至SQLAlchemy Core/ORM操作时是非常方便的,而且还可以后期动态添加索引,外键等
转载于:https://blog.51cto.com/xmdevops/1870104