pymysql实例

发布时间 2023-11-14 19:44:52作者: 贪吃极了
import pymysql

class HandleMysql:
    def __init__(self, host, user, password, db, port):
        self.conn =  pymysql.connect(host=host,
                                     user=user,
                                     password=password,
                                     db=db,
                                     port=port,
                                     charset="utf-8",
                                     cursorclass=pymysql.cursors.DictCursor)
        self.cursor = self.conn.cursor()

    def __call__(self, sql, args=None, is_more=False):
        self.cursor.execute(sql, args=args)
        self.conn.commit()
        if is_more:
            return self.cursor.fetchall()
        else:
            return self.cursor.fetchone()

    def close(self):
        self.cursor.close()
        self.conn.close()

    def test(self, name):
        sql_str = "SELECT xxx from xxx_table WHERE NAME=%s"
        result = self(sql=sql_str, args=(name))["xxx"]
        return result

if __name__ = "__main__":
        HandleMysql().test("name")