您的位置:首页 > 财经 > 产业 > 使用python MySQL 实现一个 key-value(string:json) 读写库

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

2024/10/5 21:13:33 来源:https://blog.csdn.net/cyj0919/article/details/141170460  浏览:    关键词:使用python MySQL 实现一个 key-value(string:json) 读写库

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

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com