c mysql数据库工具类_MySQL数据库工具类

、import pymysql # 导入数据库驱动模块!

classMysqlHelper():

#db= MysqlHelper('localhost',3306,'root','root','李森')

def __init__(self,host,port,user,passwd,db,charset='utf8'):

self.host=host

self.port=port

self.user=user

self.passwd=passwd

self.db=db

self.charset=charset

#self.conn=None

def connect(self):'''功能1: 获取连接'''self.conn= pymysql.connect(host=self.host,port=self.port,user=self.user,passwd=self.passwd,db=self.db,charset=self.charset)

self.cursor=self.conn.cursor()

def close(self):'''功能2:释放资源'''self.cursor.close() #关游标

self.conn.close()# 关连接

def my_execute(self,sql,params):'''增删改通用功能

:param sql: sql语句

:paramparams: 参数列表

:return: num 影响行数''' num =0#1. 打开连接

self.connect()

num= self.cursor.execute(sql,params)

self.conn.commit()

self.close() #释放资源returnnum

def get_one(self,sql,params):'''查询1条

:param sql: sql语句

:paramparams: 参数列表

:return: 1条结果''' result =None

#1.打开链接

self.connect()

#2.执行查询

self.cursor.execute(sql,params)

#3逐行抓取

result=self.cursor.fetchone()

#4.释放资源

self.close()returnresult

def get_all(self, sql,params):'''查询所有

:param sql: sql语句

:paramparams: 参数列表

:return: 1条结果''' result =()

self.connect()

self.cursor.execute(sql,params)

result=self.cursor.fetchall()

self.close()returnresultif __name__ == '__main__':

# 实例化对象

db= MysqlHelper('localhost',3306,'root','root','李森')

#增加

#insert into students values(default,'张A','男',20,'山西')''' sql = 'insert into students values(default,%s,%s,%s,%s)'

params=['张B','男',20,'山西']

num= db.my_execute(sql,params)

print(num)'''# 查1条

sql= 'select * from student_1 where age =%s'

params=(12)

result=db.get_one(sql,params) #((),())

print(result)

student_1= db.get_all(sql,params)for stu instudent_1:

print(f'名字:{stu[1]}')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值