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

发布于:2024-08-14 ⋅ 阅读:(112) ⋅ 点赞:(0)

在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` 方法分别对应设置、获取、更新和删除操作。


网站公告

今日签到

点亮在社区的每一天
去签到