• 微信公众号:美女很有趣。 工作之余,放松一下,关注即送10G+美女照片!

pymysql封装

开发技术 开发技术 5小时前 3次浏览
import pymysql


class MysqlC:

    def __init__(self, host, user, password, database):
        self.con = None
        self.arguments = {
            "host": host,
            "user": user,
            "password": password,
            "database": database,
            "charset": 'utf8'
        }

    def post(self, sql):
        with self:
            self.cursor = self.con.cursor(pymysql.cursors.DictCursor)
            try:
                data = self.cursor.execute(sql)
                self.con.commit()

                return data
            except Exception as e:
                self.con.rollback()
                return e

    def get(self, sql, one=None):
        with self:
            self.cursor = self.con.cursor(pymysql.cursors.DictCursor)
            try:
                self.cursor.execute(sql)
                if one:
                    return self.cursor.fetchone()
                else:
                    return self.cursor.fetchall()
            except Exception as e:
                return e

    def __enter__(self):
        if self.con is None:
            try:
                self.con = pymysql.connect(**self.arguments)
            except Exception:
                return "数据库连接失败!"

            return self.con

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.cursor.close()
        self.con.close()


if __name__ == '__main__':
    con = MysqlC(MysqlHost, MysqlUsername, MysqlPassword, MysqlDatabase)


    def delete():
        data = con.post("DELETE from user WHERE username ='qwe'")
        print(data)


    delete()


程序员灯塔
转载请注明原文链接:pymysql封装
喜欢 (0)