python-mysql操作 封装工具类


import pymysql


class MysqlHelper:
    def __init__(self, config):
        self.host = config["host"]
        self.port = config["port"]
        self.user = config["user"]
        self.password = config["password"]
        self.db = config["db"]
        self.charset = config["charset"]
        self.con = None
        self.cursor = None

    def create_con(self):
        """
        创建连接
        """
        try:
            self.con = pymysql.connect(host=self.host, port=self.port, user=self.user, password=self.password,
                                       database=self.db, charset='utf8')
            self.cursor = self.con.cursor()
            return True
        except Exception as e:
            print(e)
            return False

    def close_con(self):
        """
        关闭链接
        """
        if self.cursor:
            self.cursor.close()
        if self.con:
            self.con.close()

    # sql执行
    def execute_sql(self, sql):
        """
        执行插入/更新/删除语句
        """
        try:
            self.create_con()
            print(sql)
            self.cursor.execute(sql)
            self.con.commit()
        except Exception as e:
            print(e)
        finally:
            self.close_con()

    def select(self, sql, *args):
        """
        执行查询语句
        """
        try:
            self.create_con()
            print(sql)
            self.cursor.execute(sql, args)
            res = self.cursor.fetchall()
            return res
        except Exception as e:
            print(e)
            return False
        finally:
            self.close_con()


if __name__ == '__main__':
    config = {
        "host": 'localhost',
        "port": 3306,
        "user": 'root',
        "password": '123',
        "db": 'test',
        "charset": 'utf8'
    }
    db = MysqlHelper(config)
    #添加
    # db.execute_sql("insert into user (username, password) values ('username4','password4')")
    #修改
    db.execute_sql("update channellist set is_active=1 where id=2")
    #查询
    # res = db.select("SELECT * FROM channellist;")
    # print(res)


从小白到大神的蜕变~~
原文地址:https://www.cnblogs.com/tjw-bk/p/15293135.html