pymysql封装

发布时间:2022-07-03 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了pymysql封装脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
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封装全部内容,希望文章能够帮你解决pymysql封装所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:数据库