首页 > 数据库技术 > 详细

Python连接MySQL查询抽奖次数

时间:2021-09-09 16:49:09      阅读:27      评论:0      收藏:0      [点我收藏+]

最近在看“韩志超”博主的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查询抽奖次数

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!