使用python MySQL 实现一个 key-value(string:json) 读写库

在Python中,我们可以使用`pymysql`库(如果MySQL服务器版本较高,也推荐使用`mysql-connector-python`)来建立一个简单的key-value存储库,其中键是字符串,值是JSON格式的数据。这里我们创建一个基本的类来完成读写操作:

import pymysql.cursors
import json

class JsonKVStore:
    def __init__(self, host='localhost', db='test_db', user='root', password='', port=3306):
        self.conn = pymysql.connect(
            host=host,
            user=user,
            password=password,
            db=db,
            port=port,
            charset='utf8mb4',
            cursorclass=pymysql.cursors.DictCursor
        )

    def set_item(self, key, value):
        with self.conn.cursor() as cursor:
            query = "INSERT INTO kv_table (key, value) VALUES (%s, %s)"
            cursor.execute(query, (key, json.dumps(value)))
            self.conn.commit()

    def get_item(self, key):
        with self.conn.cursor() as cursor:
            query = "SELECT value FROM kv_table WHERE key=%s"
            cursor.execute(query, (key,))
            row = cursor.fetchone()
            if row:
                return json.loads(row['value'])
            else:
                return None

    def update_item(self, key, new_value):
        with self.conn.cursor() as cursor:
            query = "UPDATE kv_table SET value=%s WHERE key=%s"
            cursor.execute(query, (json.dumps(new_value), key))
            self.conn.commit()

    def delete_item(self, key):
        with self.conn.cursor() as cursor:
            query = "DELETE FROM kv_table WHERE key=%s"
            cursor.execute(query, (key,))
            self.conn.commit()

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

# 示例使用
store = JsonKVStore()
store.set_item('my_key', {'name': 'John', 'age': 30})
data = store.get_item('my_key')
store.update_item('my_key', {'name': 'Jane'})
store.delete_item('my_key')
store.close()


在这个库中,`set_item`、`get_item`、`update_item` 和 `delete_item` 方法分别对应设置、获取、更新和删除操作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值