我是靠谱客的博主 敏感棒棒糖,这篇文章主要介绍python 操作mysql数据库简单封装,现在分享给大家,希望可以做个参考。

第一步,安装pymysql库:pip install pymysql

第二步,创建一个db_utils.py

第三步,上封装好的代码:

import pymysql
from pymysql.cursors import DictCursor
class MySqlUtils:
def __init__(self, host=None, port=0, user=None, passwd=None, db=None,
charset='utf8'):
self.conn = pymysql.connect(host=host,
port=port,
user=user,
passwd=passwd,
# password也可以
db=db,
#数据库名称
charset=charset,
# 如果查询有中文需要指定数据库编码
cursorclass=DictCursor) #返回字典
self.cursor = self.conn.cursor()
def query(self, sql, args=None, fetchall=True):
self.cursor.execute(sql, args=args)
if fetchall:
#默认查询所有数据
res = self.cursor.fetchall()
else:
res = self.cursor.fetchone()
return res
def close_db(self):#关闭游标、连接
self.cursor.close()
self.conn.close()

第四步,使用:

mysql_utils = MySqlUtils(host=host, port=port, user=user, passwd=passwd, db=db)

res = mysql_utils.query("select * from 表名 where id = %s", "要查询的id") print(res) mysql_utils.close_db()

注:可以多封装一些常用的方法进去如

def query_name(self, name):
self.cursor.execute("select * from 表名 where name = %s", args=[name, ])
return self.cursor.fetchall()

调用的时候直接

mysql_utils.query_name(name="xxx")就可以了,省得每次都要写一遍sql

最后

以上就是敏感棒棒糖最近收集整理的关于python 操作mysql数据库简单封装的全部内容,更多相关python内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(118)

评论列表共有 0 条评论

立即
投稿
返回
顶部