python 数据库连接session的示例代码

@contextlib.contextmanager
def getdb():
    conn = pymysql.connect("url://server", "username", "password", "dbname", charset='utf8')
    cursor = conn.cursor()
    try:
        yield cursor
    finally:
        conn.commit()
        cursor.close()
        conn.close()

contextlib 是一个python标准库,专门为了with关键词而开发。

有了它获取数据库连接,就可以:

with getdb() as cursor:
    cursor.execute("select ...")

with 会自动调用 “yield cursor” 以后的代码,去关闭数据库连接。

 

详细介绍:https://www.cnblogs.com/pyspark/articles/8819803.html 

posted @ 2021-02-04 13:48  爱知菜  阅读(19)  评论(0编辑  收藏  举报