封装pymysql
import pymysqlclass PymysqlUtil:def __init__(self,host=\"localhost\",user=\"root\",password=\"root\",database=\"books\",port=3306,charset=\"utf8\"):self._host = hostself._user = userself._password = passwordself._database = databaseself._port = portself._charset = charsetdef __enter__(self):# 建立连接self._conn = pymysql.connect(host=self._host, user=self._user, password=self._password,database=self._database,charset=self._charset)# 获取游标self._cursor = self._conn.cursor()return self._cursordef __exit__(self, exc_type, exc_val, exc_tb):if self._cursor != None:self._cursor.close()if self._conn !=None:self._conn.close()print(\"已执行完__exit__函数中的主体代码,关闭了连接和关闭游标\")# 是指如果有别的py文件导入当前文件时,不会执行main函数中的代码if __name__ == \'__main__\':with PymysqlUtil() as cursor:sql = \"select * from t_book;\"cursor.execute(sql)print(cursor.fetchall())print(\"已退出with语法\")