import pymysql
class My_Sql:
def __init__(self, host, user, psd, name):
self.host = host
self.user = user
self.psd = psd
self.name = name
def connect(self):
self.db = pymysql.connect(self.host, self.user, self.psd, self.name)
self.cursor = self.db.cursor()
def close(self):
self.cursor.close()
self.db.close()
# 查询
def get_one(self, sql):
res = None
try:
self.connect()
self.cursor.execute(sql)
res = self.cursor.fetchone()
self.close()
except:
print("查询失败")
return res
def get_all(self, sql):
res = ()
try:
self.connect()
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.connect()
count = self.cursor.execute(sql)
self.db.commit()
self.close()
except:
print("操作失败")
self.db.rollback()
return count
if __name__ == '__main__':
s = My_Sql('localhost', 'root', 'wsw..177122', 'wakey')
print(s.get_all('select * from student where id>2'))
# 直接使用封装代码执行操作
# import AllMySql
#
# s = AllMySql("", "", "", "")
# res = s.get_all("")
# for row in res:
# print()