码迷,mamicode.com
首页 > 数据库 > 详细

python操作mysql数据库

时间:2020-03-24 23:00:23      阅读:79      评论:0      收藏:0      [点我收藏+]

标签:com   hone   mit   char   sele   count   init   self   __del__   

定义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)

python操作mysql数据库

标签:com   hone   mit   char   sele   count   init   self   __del__   

原文地址:https://blog.51cto.com/bxing/2481456

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!