从0开始python学习-53.python操作mysql、redis、mongo数据库

目录

mysql

redis

mongo


mysql

class AssertUtil:
    # 连接数据库
    def conn_mysql(self):
        self.conn = pymysql.connect(
            user="user",
            password="pwd",
            host="127.0.0.1",
            database="sd",
            port=3306
        )
        return self.conn

    # 执行sql语句
    def execute_sql(self,sql):
        # 创建数据库链接
        conn = self.conn_mysql()
        # 创建游标
        cs = conn.cursor()
        # 执行SQL
        cs.execute(sql)
        # 取值
        value = cs.fetchone()
        # 关闭资源
        cs.close()
        conn.close()
        # 返回值
        return value
        
if __name__ == "__main__":
    a = AssertUtil().execute_sql("SELECT email FROM pw_user WHERE uid = 1")
    print(a)
    print(type(a))

redis

class AssertUtil:
    # 连接redis
    def connect(self, host, port, password, db):
        self.connection = redis.Redis(
            host=host,
            port=port,
            password=password,
            db=db,
            decode_responses=True  # 将字节数据解码为字符串
        )
    # 操作redis
    def execute_command(self, command, *args):
        """
        执行Redis命令
        :param command: Redis命令
        :param args: 命令参数
        :return: 执行结果
        """
        if not hasattr(self, 'connection'):
            raise Exception("redis未连接")
        res = getattr(self.connection, command)(*args)

        # 关闭连接
        self.connection.close()
        return res

if __name__ == "__main__":
    redis_connector = AssertUtil()
    redis_connector.connect(host="192.168.0.1", port=6379, password="111111", db=0)
    # String 操作
    redis_connector.execute_command("set", "name", "4")
    print('string:'+ redis_connector.execute_command('get','name'))
    # list操作
    redis_connector.execute_command("lpush", "mylist", "item3","item4")
    redis_connector.execute_command("lpop", "mylist")
    print(redis_connector.execute_command('lrange', 'mylist',0,-1))
    # Hash 操作
    redis_connector.execute_command("hset", "myhash", "field1", "value1")
    print('hash:'+ redis_connector.execute_command("hget", "myhash", "field1"))
    print(redis_connector.execute_command('hgetall', 'myhash'))
    # Set 操作
    redis_connector.execute_command("sadd", "myset", "value1", "value2")
    print(redis_connector.execute_command("smembers", "myset"))
    # ZSet 操作
    redis_connector.execute_command("zadd", "myzset", {"value1": 1}, {"value2": 2})
    print(redis_connector.execute_command("zrangebyscore", "myzset", 0, 2))
    # 删除操作
    redis_connector.execute_command("delete","myhash")

mongo

class AssertUtil:
    def conn_mongo(self, database, host, port, username, password, auth_source):
    self.database = database
    self.client = MongoClient(
        host=host,
        port=port,
        username=username,
        password=password,
        authSource=auth_source
    )
    self.db = self.client[self.database]

def execute_mongo(self,collection, command,reslove, *args):
    """
    执行MongoDB命令
    :param database: 数据库名称
    :param collection: 集合名称
    :param command: MongoDB命令
    :param args: 命令参数
    :return: 执行结果
    """
    if not hasattr(self, 'client'):
        raise Exception("MongoDB未连接")
    self.col = self.db[collection]
    try:
        func = getattr(self.col, command)
        result = func(*args)
        if callable(reslove):
            return reslove(result)
        return result
    finally:
        self.client.close()
if __name__ == "__main__":
    mongo_connector = AssertUtil()
    mongo_connector.conn_mongo(database="test", host="192.168.0.1", port=27017, username="admin", password="1111", auth_source="admin")
    # 插入文档
    mongo_connector.execute_mongo("insert_one",None,{"model_id": "gpt","nickname": "ces","avatar": "1111"})
    # 查询文档
    print(mongo_connector.execute_mongo("test1","find_one",None,{"model_id": "gpt-3.5-turbo"}))
    # 查询多条文档
    def reslove(results):
        for result in results:
            print(result)
    res = mongo_connector.execute_mongo("test1","find", reslove,{"model_id": "gpt"})
    # 更新文档
    mongo_connector.execute_mongo("test1","update_one", None,{"model_id": "gpt11"}, {"$set": {"nickname": "aaaaa"}})
    # 删除文档
    mongo_connector.execute_mongo("test1","delete_one",  None,{"model_id": "model_id"})

  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值