import pymysql
from pymysql.cursors import DictCursor
class NoDataBaseException(Exception):
pass
class DBHelper:
def __init__(self, database=None, host="localhost", port=3306, username="root", password="1234"):
if database:
self.conn = pymysql.connect(
host=host,
port=port,
user=username,
password=password,
database=database
)
else:
raise NoDataBaseException("没有提供正确的数据库")
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
return self.conn.close()
def _change(self, sql, *args, isInsert=False):
cursor = self.conn.cursor(cursor=DictCursor)
try:
rownum = cursor.execute(sql, args)
self.conn.commit()
if isInsert:
return cursor.lastrowid
else:
return rownum
except Exception as e:
print("报错了", e)
self.conn.rollback()
finally:
cursor.close()
def insert(self, sql, *args):
return self._change(sql, *args, isInsert=True)
def update(self, sql, *args):
return self._change(sql, *args)
def delete(self, sql, *args):
return self._change(sql, *args)
def query_list(self, sql, *args):
cursor = self.conn.cursor(cursor=DictCursor)
try:
cursor.execute(sql, args)
result = cursor.fetchall()
return result
finally:
cursor.close()
def query_one(self, sql, *args):
cursor = self.conn.cursor(cursor=DictCursor)
try:
cursor.execute(sql, args)
result = cursor.fetchone()
return result
finally:
cursor.close()
if __name__ == '__main__':
with DBHelper("spider") as db: # ""里面填数据库库名 where 后面的参数 %s ,
pass
# 添加数据
# result = db.insert('insert into stu_new (sname, sgender, sage, score, class) values ("赵e山", 2, 165, 277, "八年六班")')
# print(result)
# 修改数据 delete 和 update 俩个一样,调那个都可以
# result = db.update("update stu_new set sname='王八' where sno = %s", 13)
# print(result)
# 删除数据
# result = db.delete("delete from stu where sno = %s", 13)
# print(result)
# 查看所有数据
# result = db.query_list("select * from stu1")
# print(result)
# result = db.query_list("select * from stu1 where gender=%s and address like %s", 1, "%四川%")
# print(result)
# # 查看一条数据
# result = db.query_one("select * from stu_new where sno=%s", 9)
# print(result)