- 标题:pymysql 链接封装。
- 实战: 这个标题是基于日常开发自己写的一些小模块,虽然没多少技术含量,但是我喜欢用
- 个人:最近在学习小程序。前端好难啊
拿来即用 下面是代码
import pymysql
import sys
class Config(object):
@staticmethod
def get_config(name):
config = {
'localhost': {
'host': '127.0.0.1',
'user': 'mysql',
'password': 'mysql',
'database': 'mysql',
'port': 3306
}
}
return config[name]
class UseDB(object):
def __init__(self, name):
self.__conn = self.build_conn(name)
self.__cursor = self.__conn.cursor()
@property
def conn(self):
return self.__conn
def build_conn(self, name):
try:
config = Config.get_config(name)
conn = pymysql.connect(host=config["host"], user=config["user"], passwd=config["password"],
db=config["database"], charset='utf8')
return conn
except Exception as e:
print('Something wrong: %s' % format(e))
def getData(self, sql, type="all"):
self.__cursor.execute(sql)
if type != "all":
return self.__cursor.fetchone()
return self.__cursor.fetchall()
def postData(self, sql):
try:
self.__cursor.execute(sql)
self.conn.commit()
except Exception as e:
self.conn.rollback()
def close(self):
self.conn.close()
class ToExecute(object):
def __init__(self, db1, db2):
self.db1 = UseDB(db1)
self.db2 = UseDB(db2)
def xxx(self):
pass
to = ToExecute(db1='',db2='')
网友评论