当前位置:网站首页>【踩坑记录】数据库连接未关闭连接,释放资源的坑
【踩坑记录】数据库连接未关闭连接,释放资源的坑
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()
边栏推荐
- 使用aggregation API扩展你的kubernetes API
- Pyqt5 setting window top left Icon
- 2020 smart power plant industry insight white paper
- Difference between MySQL read committed and repeatability
- Ansible uses ordinary users to manage the controlled end
- sklearn sklearn中classification_report&精确度/召回率/F1值
- SQL statement error caused by the same SQL table name and function name.
- mysql读已提交和可重复度区别
- mongodb 4. X binding multiple IP startup errors
- mongodb 4.x绑定多个ip启动报错
猜你喜欢

Day_ 09 smart health project - mobile terminal development - Mobile quick login and permission control

Day_09 传智健康项目-移动端开发-手机快速登录、权限控制

基于T5L1的小型PLC设计方案

Visual studio debugging tips

【Leetcode】431. Encode n-ary tree to binary tree (difficult)
![[open source project] excel export Lua configuration table tool](/img/3a/8e831c4216494d5497928bae21523b.png)
[open source project] excel export Lua configuration table tool

图解 Google V8 # 18 :异步编程(一):V8是如何实现微任务的?

(1)基础学习——vim编辑器常用快捷操作命令

Day_ 13 smart health project - Chapter 13

射频基础理论(dB)
随机推荐
Leetcode topic resolution valid Sudoku
Day_ 08 smart health project - mobile terminal development - physical examination appointment
Pyinstaller package exe setting icon is not displayed
Design scheme of Small PLC based on t5l1
Network packet capturing tcpdump User Guide
百度URL参数之LINK?URL参数加密解密研究(代码实例)
又到半年总结时,IT人只想躺平
Remove duplicates from sorted list II of leetcode topic resolution
Leetcode topic resolution single number
Gplearn appears assignment destination is read only
Jour 13 Projet de santé mentale - chapitre 13
程序员的真实想法 | 每日趣闻
I heard you want to embed ppt on WordPress website?
Day_ 09 smart health project - mobile terminal development - Mobile quick login and permission control
[focus on growth and build a dream for the future] - TDP year-end event, three chapters go to the Spring Festival!
Summary of ant usage (I): using ant to automatically package apk
索引——MySQL
Long substring without repeating characters for leetcode topic resolution
[vivado] xilinxcedstore introduction
Ant Usage Summary (II): description of related commands