Context manager for Python's MySQLdb

后端 未结 2 661
猫巷女王i
猫巷女王i 2020-12-03 00:01

I am used to (spoiled by?) python\'s SQLite interface to deal with SQL databases. One nice feature in python\'s SQLite\'s API the \"context manager,\" i.e., python\'s

2条回答
  •  死守一世寂寞
    2020-12-03 00:41

    Think things have changed since this question was originally asked. Somewhat confusingly (from my point of view at least), for recent versions of MySQLdb, if you use a connection in a context you get a cursor (as per the oursql example), not something that closes automatically (as you would if you opened a file for instance).

    Here's what I do:

    from contextlib import closing
    with closing(getConnection()) as conn: #ensure that the connection is closed
        with conn as cursor:               #cursor will now auto-commit
            cursor.execute('SELECT * FROM tablename')
    

提交回复
热议问题