python操作mysql数据库

醉酒当歌 提交于 2020-03-24 22:46:03

定义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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!