定义mysql类
class MySQL(object):
conn = None
cursor = None
def __init__(self,host,account,passwd,db,charset='utf8',port=3306):
self.host=host
self.account=account
self.passwd=passwd
self.db=db
self.charset=charset
self.port=port
self.connect()
def connect(self):
try:
self.conn = MySQLdb.connect(self.host, self.account, self.passwd, self.db, charset=self.charset)
self.cursor = self.conn.cursor()
except Exception as e:
logger.error(u'数据库连接失败:%s' % e)
sys.exit(0)
def close(self):
self.cursor.close()
self.conn.close()
def insert(self,query):
return self.__edit(query)
def delete(self,query):
return self.__edit(query)
def update(self,query):
return self.__edit(query)
def __edit(self,query):
count = 0
try:
count = self.cursor.execute(query)
self.conn.commit()
except Exception as e:
self.conn.rollback()
logger.error(e)
logger.error('SQL:%s' % query)
return count
def getOne(self,query):
try:
self.cursor.execute(query)
return self.cursor.fetchone()
except Exception as e:
logger.error(u'错误:%s' % e)
logger.error("执行的SQL语句为:%s" % query)
def getAll(self,query):
try:
self.cursor.execute(query)
return self.cursor.fetchall()
except Exception as e:
logger.error(u'错误:%s' % e)
logger.error("执行的SQL语句为:%s" % query)
def __del__(self):
if self.conn:
self.close()
实例化
constring=('127.0.0.1','user','passwd','db')
db=mysql(constring)
执行某个查询操作
query='select * from table_name'
db.getAll(query)
来源:51CTO
作者:海底小纵队
链接:https://blog.51cto.com/bxing/2481456