首先导入pymysql 模块
from pymysql import connect
class DBOpen(object):
# 初始化操作
def init(self, database_name):
# 创建Connecttion连接
self.conn = connect(host=”localhost”, port=3306, user=”xxx”, password=”xxxl”, database=”xxx”)
# 获取游标对象
self.cs = self.conn.cursor()
# 返回操作的对象
def __enter__(self):
return self.cs
# 退出
def __exit__(self, exc_type, exc_val, exc_tb):
self.cs.close()
self.conn.close()
with DBOpen(“xxx”) as cs:
sql = “”“select * from xxx”“”
cs.execute()
# 得到数据
data = cs.fetchall()
处理数据
for temp in data:
print(temp)