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)
从小白到大神的蜕变~~
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步