python-mysql操作 封装工具类
import pymysql
class MysqlHelper:
def __init__(self, config):
self.host = config["host"]
self.port = config["port"]
self.user = config["user"]
self.password = config["password"]
self.db = config["db"]
self.charset = config["charset"]
self.con = None
self.cursor = None
def create_con(self):
"""
创建连接
"""
try:
self.con = pymysql.connect(host=self.host, port=self.port, user=self.user, password=self.password,
database=self.db, charset='utf8')
self.cursor = self.con.cursor()
return True
except Exception as e:
print(e)
return False
def close_con(self):
"""
关闭链接
"""
if self.cursor:
self.cursor.close()
if self.con:
self.con.close()
# sql执行
def execute_sql(self, sql):
"""
执行插入/更新/删除语句
"""
try:
self.create_con()
print(sql)
self.cursor.execute(sql)
self.con.commit()
except Exception as e:
print(e)
finally:
self.close_con()
def select(self, sql, *args):
"""
执行查询语句
"""
try:
self.create_con()
print(sql)
self.cursor.execute(sql, args)
res = self.cursor.fetchall()
return res
except Exception as e:
print(e)
return False
finally:
self.close_con()
if __name__ == '__main__':
config = {
"host": 'localhost',
"port": 3306,
"user": 'root',
"password": '123',
"db": 'test',
"charset": 'utf8'
}
db = MysqlHelper(config)
#添加
# db.execute_sql("insert into user (username, password) values ('username4','password4')")
#修改
db.execute_sql("update channellist set is_active=1 where id=2")
#查询
# res = db.select("SELECT * FROM channellist;")
# print(res)
作者:就学45分钟
出处:https://www.cnblogs.com/tjw-bk/p/15293135.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。您的鼓励是博主的最大动力!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了