推荐学习书目
› 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 · Jun 17, 2018 · 4018 views
    This topic created in 3048 days ago, the information mentioned may be changed or developed.
    我测试过。如果每次使用就创建 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  
       Jun 17, 2018 via Android
    都是池化管理 使用链接池是基础也是常规做法
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2773 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 98ms · UTC 15:51 · PVG 23:51 · LAX 08:51 · JFK 11:51
    ♥ Do have faith in what you're doing.