```
importpymysqlimportcontextlib#定义上下文管理器,连接后自动关闭连接@contextlib.contextmanager
def mysql(host='127.0.0.1',port=3306,user='root',passwd='',db='tkq1',charset='utf8'):conn=pymysql.connect(host=host,port=port,user=user,passwd=passwd,db=db,charset=charset)
cursor=conn.cursor(cursor=pymysql.cursors.DictCursor)
try:
yield cursor
finally:
conn.commit()
cursor.close()
conn.close()
# 执行sql
with mysql() as cursor:
print(cursor)
row_count = cursor.execute("select * from tb7")
row_1=cursor.fetchone()
printrow_count,row_1
```
网友评论