当前位置:网站首页>[pit stepping record] a pit where the database connection is not closed and resources are released

[pit stepping record] a pit where the database connection is not closed and resources are released

2022-06-23 07:32:00 Stoblie

Today we don't talk about needs , In the code review when , See such a piece of code . Let's see , What problems might this database code cause ?

def execute(self, sql):
    """ perform SQL Sentence method """
    try:
        conn = self.client.connection()
        cursor = conn.cursor()
        cursor.execute(sql)
        result = cur.fetchall()
        cur.close()
        conn.close()
        return result
    except Exception as e:
        log.error(e)
        raise e

Write the closing database connection in try Inside , If the query is abnormal , Can the connection and cursor be released ?

Whether the connection will occupy system resources for a long time until it is recycled over time ?

Under the condition of limiting the size of the connection pool , If this query SQL Too many exceptions , Exceeded the connection pool limit , Whether other normal queries cannot be executed ?

It is believed that this is a pit that most developers are easy to tread on , Why do you say that ? Now there are many perfect frameworks , Help us do it ORM, Most development has long relied on frameworks , The business is well written but the foundation is lost .

The following is the version that I think is OK , Welcome to advise .

try:
    conn = self.client.connection()
    cur = conn.cursor()
    cur.execute(sql)
    result = cur.fetchall()
except Exception as e:
    log.error(e)
    raise e
else:
    return result
finally:
    if cur:
        cur.close()
    if conn:
        conn.close()

 

 

原网站

版权声明
本文为[Stoblie]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206230501156002.html