from pymysql import *
class Database(object):
def __init__(self,name,password):
# 创建self.conn连接
self.conn = connect(host='localhost',port=3306,database=str(name),user='root',password=str(password),charset='utf8')
# 获得self.cursor对象
self.cursor = self.conn.cursor()
def __enter__(self):
return self.cursor # 返回self.cursor对象
def __exit__(self, exc_type, exc_val, exc_tb):
self.cursor.close() # 关闭self.cursor对象
self.conn.close() # 关闭self.conn连接
with Database('zzj_01','mysql') as db:
db.execute(""" select * from students; """) # 执行sql语句
content = db.fetchall() # 获取数据
# 遍历获取到的数据,打印每一条数据
for info in content:
print(info)