news_server/mod/mysql.py

49 lines
1.4 KiB
Python
Raw Permalink Normal View History

2019-12-29 21:33:37 +08:00
# -*- coding: UTF-8 -*-
import pymysql
class Mysql(object):
def __init__(self):
#配置mysql数据库信息
config = {
'host': '127.0.0.1',
'port': 3306,
'user': 'root',
'passwd': '123456',
'db': 'news',
'charset': 'utf8'
}
self.host = config['host']
self.username = config['user']
self.password = config['passwd']
self.port = config['port']
self.db = config['db']
self.con = None
self.cursor = None
try:
self.conn = pymysql.connect(**config)
# 所有的查询,都在连接 con 的一个模块 cursor 上面运行的
self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
except:
print("DataBase connect error,please check the db config.")
def exeCommit(self, sql=''):
"""执行数据库sql语句针对更新,删除,事务等操作失败时回滚
"""
try:
execute = self.cursor.execute(sql)
self.conn.commit()
return execute
except pymysql.Error as e:
self.conn.rollback()
error = 'MySQL execute failed! ERROR (%s): %s' % (e.args[0], e.args[1])
print("error:", error)
return error
def __del__(self):
# 关闭cursor对象
self.cursor.close()
self.conn.close()