best way to run python generator cleanup code

后端 未结 3 706
鱼传尺愫
鱼传尺愫 2021-01-14 00:41

I\'m trying to write a generator function that gets rows out of a database and returns them one at a time. However, I\'m not sure if the cleanup code marked ** below execute

3条回答
  •  暖寄归人
    2021-01-14 00:51

    Your version will run dbc.close() as soon as d is None, but not if an exception gets raised. You need a finally clause. This version is guaranteed to run dbc.close() even if an exception gets raised:

    try:   
        myDB = MySQLdb.connect(host=..., port=..., user=..., passwd=..., db=...)   
        dbc = myDB.cursor()
        dbc.execute(stmt)
        d = "asdf"
        while d is not None:
            d = dbc.fetchone() #can also use fetchmany() to be more efficient
            yield d
    except MySQLdb.Error, msg:
        print("MYSQL ERROR!")
        print msg
    finally:
        dbc.close()
    

提交回复
热议问题