33 lines
1008 B
Python
33 lines
1008 B
Python
|
|
import pymysql
|
||
|
|
from sqlalchemy import create_engine
|
||
|
|
|
||
|
|
|
||
|
|
class MySQLconnect():
|
||
|
|
def __init__(self, dbname: str):
|
||
|
|
if isinstance(dbname, str):
|
||
|
|
self.dbname = dbname
|
||
|
|
self.host = '192.168.100.33'
|
||
|
|
else:
|
||
|
|
raise TypeError("dbname must be a string")
|
||
|
|
|
||
|
|
def __enter__(self):
|
||
|
|
self.eng = self.engine()
|
||
|
|
self.con = self.connect()
|
||
|
|
self.cur = self.con.cursor()
|
||
|
|
return self
|
||
|
|
|
||
|
|
def __exit__(self, exc_type, exc_val, exc_tb):
|
||
|
|
self.eng.dispose()
|
||
|
|
self.cur.close()
|
||
|
|
self.con.close()
|
||
|
|
if exc_val:
|
||
|
|
raise
|
||
|
|
|
||
|
|
def engine(self):
|
||
|
|
return create_engine("mysql+pymysql://zhenggantian:123456@" + self.host + f":3306/{self.dbname}",
|
||
|
|
pool_size=10, max_overflow=5, pool_recycle=3600)
|
||
|
|
|
||
|
|
def connect(self):
|
||
|
|
return pymysql.connect(host=self.host, port=3306, database=self.dbname, user="zhenggantian", password="123456",
|
||
|
|
charset="utf8")
|