- with 语句的目的是简化try/finally ,即便由于异常,return,sys.exit()调用而终止,也会执行指定的操作
- 上下文管理器协议包含__enter__和__exit__ 两个方法
- with 语句开始执行时会在上下文管理器对象上调用__enter__方法
- with 语句运行结构后会在上下文管理器对象上调用__exit__方法,以此扮演finally子句的角色
示例:
import pymysql.cursors
# Connect to the database
connection = pymysql.connect(host='localhost',
user='user',
password='passwd',
database='db',
cursorclass=pymysql.cursors.DictCursor)
with connection:
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
cursor.execute(sql, ('[email protected]', 'very-secret'))
# connection is not autocommit by default. So you must commit to save
# your changes.
connection.commit()
with connection.cursor() as cursor:
# Read a single record
sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
cursor.execute(sql, ('[email protected]',))
result = cursor.fetchone()
print(result)
connection 对象实现了上下文管理器协议:
cursor 对象也实现了上下文管理器协议:
标签:__,管理器,Python,cursor,connection,sql,上下文 From: https://www.cnblogs.com/czzz/p/16864451.html