当前位置:网站首页>【踩坑记录】数据库连接未关闭连接,释放资源的坑
【踩坑记录】数据库连接未关闭连接,释放资源的坑
2022-06-23 05:01:00 【士多碧莉】
今天不聊需求,在代码review时,看到这么一段代码。大家来看一下,这段数据库代码可能引发什么问题?
def execute(self, sql):
"""执行SQL语句方法"""
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把关闭数据库连接写在try里面,要是在查询的时候异常了,连接和游标能释放么?
是否该连接会长期占用系统资源直到被超时回收?
在限定连接池大小的条件下,如果这种查询SQL异常过多,超过了连接池限定大小,是否会导致其他正常查询无法执行?
相信这是大部分开发都容易踩的坑,为什么这么说呢?现在有很多完善的框架,帮我们做好了ORM,大部分开发长期依赖框架,业务写的很优秀但却把基础丢了。
下面是个人认为没什么问题的版本,欢迎指教。
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()
边栏推荐
- Ansible uses ordinary users to manage the controlled end
- 100-300 cases of single chip microcomputer program (detailed explanation of notes)
- 机器学习3-岭回归,Lasso,变量选择技术
- 给定二叉树的某个节点,返回该节点的后继节点
- 射频内容学习
- Vite learning (I) - Introduction
- CPU的功能和基本结构
- Link of Baidu URL parameter? Research on URL parameter encryption and decryption (code example)
- 密码学系列之:PKI的证书格式表示X.509
- Day_ 13 smart health project - Chapter 13
猜你喜欢

Pyqt5 setting window top left Icon

Day_04 傳智健康項目-預約管理-套餐管理

Day_ 11 smart communication health project - graphic report and poi Report

机器学习3-岭回归,Lasso,变量选择技术

Jour 04 projet de santé mentale - gestion des rendez - vous - gestion des forfaits

Day_12 传智健康项目-JasperReports

Day_06 传智健康项目-移动端开发-体检预约

Day_05 传智健康项目-预约管理-预约设置

Day_02 传智健康项目-预约管理-检查项管理

Day_ 07 smart communication health project FreeMarker
随机推荐
程序员的真实想法 | 每日趣闻
Summary of ant usage (I): using ant to automatically package apk
Layer 2技术方案进展情况
Introduction to JVM principle
For non dpdk kvm1.0 machines, set init Maxrxbuffers changed from 256 to 1024 to improve packet receiving capacity
Fastdata pole | insight report on e-commerce consumption of young Chinese users 2021
How to add libraries for Arduino ide installation
CVE-2021-20038
Global attribute lang attribute
Detailed explanation of redis persistence, master-slave and sentry architecture
Redis sentry
Jour 04 projet de santé mentale - gestion des rendez - vous - gestion des forfaits
Day_ 02 smart communication health project - appointment management - inspection item management
Word pattern for leetcode topic analysis
Leetcode topic resolution valid Sudoku
Fraction to recursing decimal
Tcp/ip explanation (version 2) notes / 3 link layer / 3.4 bridge and switch
[vivado] xilinxcedstore introduction
Difference between MySQL read committed and repeatability
sklearn sklearn中classification_report&精确度/召回率/F1值