阅读 66

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)

代码执行结果:

 

原文:https://www.cnblogs.com/keleqq/p/15242458.html

文章分类
百科问答
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐