Python连接MySQL查询抽奖次数

最近在看“韩志超”博主的Python接口测试文档,根据博主写的Python连接数据库文章来操作,终于顺利连接上并查到自己想要的数据了。

import pymysql

class DB:

    def __init__(self):

        # 获取连接方法

        self.conn = pymysql.connect(
            host='xxx.xx.xx.x',
            port=3306,
            user='root',
            password='xxx123',
            db='mall_prize',
            charset='utf8')
        self.cur = self.conn.cursor()

    def __del__(self):  # 析构函数,实例删除时触发
        self.cur.close()
        self.conn.close()

    def query(self, sql):  # 查询数据库
        self.cur.execute(sql)
        return self.cur.fetchall()

    def exec(self, sql):
        try:
            self.cur.execute(sql)
            self.conn.commit()
        except Exception as e:
            self.conn.rollback()
            print(str(e))

        # 封装常用数据库操作
    def check_user(self, account_id):
        # 注意SQL中''号嵌套的问题
        #result =self.query(f"select * from mall_activity_prize_log where activity_id = 332 and account_id = '{account_id}'" )
        result = self.query(f"select account_id as 用户, count(*) as 抽奖次数 , activity_id 活动ID "
                            f"from mall_activity_prize_log "
                            f"group by account_id , activity_id having account_id = '{account_id}'")
        print(result)
        return result

def del_user(self, account_id):  # 删除抽奖纪录
    self.exec(f"delete from mall_activity_prize_log where account_id = '{account_id}'")

if __name__ == '__main__':
    db = DB()
    account_id = '1D6CC100-xxxx-xxxx-9F08-4FF336308371'  # 输入用户id,查询用户的抽奖次数
    db.check_user(account_id)

代码执行结果:

Python连接MySQL查询抽奖次数

 

上一篇:读mysql8 CookBook的零碎整理5——mysql 比较好的书籍


下一篇:同步方法及同步块