首先,我们连接建立好的数据库:
#导包
from pymysql import *
class DB(object):
def __init__(self,databasename,password):
# 1. 连接数据
# 创建Connection连接
self.conn = connect(host='localhost', port=3306, database=str(databasename), user='root', password=str(password), charset='utf8')
# 获得Cursor对象
self.cs1 = self.conn.cursor()
def __enter__(self):
return self.cs1;
def __exit__(self, exc_type, exc_val, exc_tb):
self.cs1.close()
self.conn.close()
用‘with’打开数据库:
with DB("jing","mysql") as db:
db.execute("select * from goods_brands; ")content = db.fetchall()
print(content)