当前位置:网站首页>PyMySQL利用游标操作数据库方法封装!!!
PyMySQL利用游标操作数据库方法封装!!!
2022-06-11 18:53:00 【是南巷的花猫啊】
我把所有的增删查改基本功能都封装好了,直接方法调用就可以!!!
代码部分:
import pymysql # 导入操作MySQL数据库的模块
userName = "" # 记录用户名
# 打开数据库连接
def open():
db = pymysql.connect(host="localhost", user="root", password="196811", database="db_student", charset="utf8")
return db # 返回连接对象
# 执行数据库的增、删、改操作
def exec(sql, values):
db = open() # 连接数据库
cursor = db.cursor() # 使用cursor()方法获取操作游标
try:
cursor.execute(sql, values) # 执行增删改的SQL语句
db.commit() # 提交数据
return 1 # 执行成功
except:
db.rollback() # 发生错误时回滚
return 0 # 执行失败
finally:
cursor.close() # 关闭游标
db.close() # 关闭数据库连接
# 带参数的精确查询
def query(sql, *keys):
db=open() # 连接数据库
cursor = db.cursor() # 使用cursor()方法获取操作游标
cursor.execute(sql, keys) # 执行查询SQL语句
result = cursor.fetchall() # 记录查询结果
cursor.close() # 关闭游标
db.close() # 关闭数据库连接
return result # 返回查询结果
# 不带参数的模糊查询
def query2(sql):
db = open() # 连接数据库
cursor = db.cursor() # 使用cursor()方法获取操作游标
cursor.execute(sql) # 执行查询SQL语句
result = cursor.fetchall() # 记录查询结果
cursor.close() # 关闭游标
db.close() # 关闭数据库连接
return result # 返回查询结果
边栏推荐
- ASEMI的MOS管25N120在不同应用场景的表现
- *Jetpack notes understanding of lifecycle ViewModel and livedata
- *Use of jetpack notes room
- 一款自适应的聊天网站-匿名在线聊天室PHP源码
- Quanzhi T3 development board (4-core arm cortex-a7) - detailed explanation of logo display during system startup
- Niu Ke swipes the question -- converting a string to an integer
- 防止敌方坦克重叠
- WWDC22 开发者需要关注的重点内容
- Cf:b. array determinations
- On the sequence traversal of binary tree
猜你喜欢

cf:A. Print a Pedestal (Codeforces logo?)【简单遍历模拟】

Gmail:如何撤回发出的邮件?

Swagger2 easy to use

牛客刷题——不要二

Uni app Muke hot search project (I) production of tabbar
![leetcode:926. Flip the string to monotonically increasing [prefix and + analog analysis]](/img/e8/a43b397155c6957b142dd0feb59885.png)
leetcode:926. Flip the string to monotonically increasing [prefix and + analog analysis]

非递归实现二叉树的前、中、后序遍历

SQL注入漏洞学习之一:phpstudy集成环境搭建DVWA靶场

The nearest common ancestor of binary tree

cf:G. Count the Trains【sortedset + bisect + 模拟维持严格递减序列】
随机推荐
全志科技T3开发板(4核ARM Cortex-A7)——视频开发案例
软件开发的整体流程
力扣刷题——二叉树的层序遍历Ⅱ
2022成年礼,致每一位高考学子
KMP!你值得拥有!!! 直接运行直接跑!
Let our tanks move happily
己方坦克发射子弹
Function development of user information management
Realize that you can continue to play
Force deduction 33 questions, search rotation sorting array
实现可以继续上局
Crop disease detection using image processing technology and convolutional neural network (CNN)
On the sequence traversal of binary tree
公共字段自动填充,你了解吗
全志科技T3开发板(4核ARM Cortex-A7)——MQTT通信协议案例
让我们的坦克欢快的动起来吧
cf:B. Array Decrements【模拟】
Make a static tank
SAP UI5 里 XML 视图根节点运行时实例化的分析
Undefined reference to 'g2o:: vertexe3:: vertexe3()'