python中利用上下文管理器来实现mysql数据库的封装

from pymysql import connect

class DB(object):

def __init__(self, password, database):

# 1.连接数据库

self.conn = connect(host='localhost', port=3306, user='root', password=str(password), database=str(database),

charset='utf8')

# 2.创建游标

self.cs = self.conn.cursor()

def __enter__(self):

return self.cs

def __exit__(self, exc_type, exc_val, exc_tb):

# 3.关闭

self.cs.close()

self.conn.close()

# 利用上下文管理器来封装的数据库的操作,只需要传入密码和需要连接的数据库就可以了

with DB("mysql", "student_selection") as db:

# 需要执行的数据库操作(sql语句)

db.execute("select * from student; ")

# 循环取出查找的数据

data = db.fetchall()

for content in data:

print(content)