import pymysql
class DBHelper():
def __init__(self,host, user, passwd, dbName):
self.host = host
self.user = user
self.passwd = passwd
self.dbName = dbName
def connet(self):
#连接到数据库
self.db = pymysql.connect(self.host,self.user,self.passwd,self.dbName)
#创建游标
self.cursor = self.db.cursor()
def close(self):
self.cursor.close()
self.db.close()
#查询一条数据
def get_one(self, sql):
res = None
try:
self.connet()
self.cursor.execute(sql)
res = self.cursor.fetchone()
self.close()
except:
print("查询失败")
return res
#得到所有的数据
def get_all(self, sql):
res = ()
try:
self.connet()
self.cursor.execute(sql)
res = self.cursor.fetchall()
self.close()
except:
print("查询失败")
return res
#插入
def insert(self, sql):
return self.__edit(sql)
#更新
def update(self, sql):
return self.__edit(sql)
#删除
def delete(self, sql):
return self.__edit(sql)
def __edit(self,sql):
count = 0
try:
self.connet()
count = self.cursor.execute(sql)
self.db.commit()
self.close()
except:
print("事物提交失败")
self.db.rollback()
return count
if __name__ == '__main__':
dbh = DbHelper(host='localhost',username='root',password='123456',database='stu')
#查询当前用户
#res = dbh.get_one('select user()')
#res = dbh.insert_data("insert into student values(0,'谭松韵',29,0,99)")
#res = dbh.get_all('select * from student')
#res = dbh.update_data("update student set name='周杰伦' where id=4")
res = dbh.delete_data("delete from student where id>60")
print(res)
python封装mysql
最新推荐文章于 2023-11-30 18:11:09 发布