定义配置文件 config.py
class LocalDB:
class Local1:
info = {
"Host": "127.0.0.1",
"Port": "3306",
"UserName": "root",
"Password": "1122",
}
information_schema = "information_schema"
mysql = "mysql"
performance_schema = "performance_schema"
sys = "sys"
test = "test"
class Local2:
info = {
"Host": "127.0.0.2",
"Port": "3306",
"UserName": "root",
"Password": "1122",
}
information_schema = "information_schema"
mysql = "mysql"
performance_schema = "performance_schema"
sys = "sys"
test = "test"
封装pymysql
class DBConn(object):
def __init__(self, db_setting, db_name):
try:
host = db_setting["Host"]
port = db_setting["Port"]
user_name = db_setting["UserName"]
password = db_setting["Password"]
self.engine = create_engine("mysql+pymysql://" + user_name + ":" + quote_plus(password) + "@" + host + ":" + port + "/" + db_name + "?charset=utf8")
self.conn = pymysql.connect(host=host, port=int(port), user=user_name, password=password, database=db_name, charset="utf8", connect_timeout=180)
self.cur = self.conn.cursor()
session = sessionmaker(bind=self.engine) # engine 是数据库连接对象
self.session = session()
except Exception as e:
raise ConnectionError(f"数据库连接失败,{str(e)}")
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
def close(self):
self.engine.dispose()
self.cur.close()
self.conn.close()
self.session.close()
def fetchone(self, sql):
self.cur.execute(sql)
data = self.cur.fetchone()
return data
def fetchall(self, sql):
self.cur.execute(sql)
data = self.cur.fetchall()
return data
def get_columns(self):
return [i[0] for i in self.cur.description]
使用示例
with DBConn(LocalDB.Local1.info, LocalDB.Local1.test) as local1_db:
sql = "show tables;"
for table_name in local1_db.fetchall(sql):
print(table_name[0])