V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
zhizunbao1984
V2EX  ›  Python

请问 pymysql 如何安全的关闭连接?

  •  
  •   zhizunbao1984 · 2018-06-17 19:34:00 +08:00 · 3473 次点击
    这是一个创建于 2137 天前的主题,其中的信息可能已经有所发展或是发生改变。
    我测试过。如果每次使用就创建 connection 对象并关闭要比一次创建用完再关闭慢 3 倍,但我的代码可能会像下面这样。如何安全关闭呢?目前想到的是把它封装到一个类并实现这个类的__del__。在 del 里关闭。但我想直接用函数,并且我觉得我没必要封装进去。如果是这样该如何弄?

    connection = pymysql.connect(host='localhost',
    user='root',
    password='password',
    db='blog',
    charset='utf8',
    cursorclass=pymysql.cursors.DictCursor)


    with connection.cursor() as cursor:
    # Read a single record
    sql = "SELECT * from categories"
    cursor.execute(sql)
    result = cursor.fetchall()
    print(result)
    connection.close()

    #做其它事 ..............................
    #这里可能直接返回
    #执行下边出错

    with connection.cursor() as cursor:
    # Read a single record
    sql = "SELECT * from categories"
    cursor.execute(sql)
    result = cursor.fetchall()
    print(result)
    lolizeppelin
        1
    lolizeppelin  
       2018-06-17 22:56:14 +08:00 via Android
    都是池化管理 使用链接池是基础也是常规做法
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1072 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 18:54 · PVG 02:54 · LAX 11:54 · JFK 14:54
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.