You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
70 lines
1.8 KiB
70 lines
1.8 KiB
import pymysql
|
|
import logging
|
|
|
|
# 创见日志对象
|
|
logger = logging.getLogger("db_log.txt")
|
|
|
|
#输出格式
|
|
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
|
|
|
|
#将文件输出的磁盘
|
|
file_handler = logging.FileHandler('db_log.txt')
|
|
|
|
#设置为设定好的输出个数
|
|
file_handler.setFormatter(formatter)
|
|
|
|
#设置文件等级
|
|
logger.setLevel(logging.INFO)
|
|
|
|
#添加进logger
|
|
logger.addHandler(file_handler)
|
|
|
|
class DBHelper:
|
|
def __init__(self, host='localhost', port=3306, user='root', password='123456', db='qwq'):
|
|
self.host = host
|
|
self.user = user
|
|
self.password = password
|
|
self.db = db
|
|
self.port = port
|
|
self.conn = None
|
|
self.cur = None
|
|
|
|
def connect(self):
|
|
try:
|
|
self.conn = pymysql.connect(host=self.host, port=self.port, user=self.user, password=self.password, db=self.db)
|
|
except:
|
|
logger.error('connect Error')
|
|
return False
|
|
self.cur = self.conn.cursor()
|
|
return True
|
|
|
|
def execute(self, sql, params=None):
|
|
if not self.connect():
|
|
return False
|
|
try:
|
|
if self.conn and self.cur:
|
|
self.cur.execute(sql, params)
|
|
self.conn.commit()
|
|
except:
|
|
logger.error(str(sql))
|
|
return False
|
|
return True
|
|
|
|
def fetchCount(self, sql, params=None):
|
|
if not self.connect():
|
|
return False
|
|
self.execute(sql, params)
|
|
return self.cur.fetchone()
|
|
|
|
def close(self):
|
|
self.cur.close()
|
|
self.conn.close()
|
|
|
|
if __name__ == '__main__':
|
|
db = DBHelper()
|
|
sql = 'create table films(title varchar(50), actor varchar(200), time varchar(100));'
|
|
db.execute(sql, None)
|
|
db.close()
|
|
logger.removeHandler(file_handler)
|
|
|