list集合怎么存数据库
时间: 2023-09-24 14:02:51 浏览: 48
要将list集合存储到数据库中,需要将list转换为字符串或者字节数组。常见的做法是使用json库将list转换为json字符串,然后将json字符串存储到数据库的text类型字段中。
例如,在Python中可以使用如下代码将list转换为json字符串并存储到MySQL数据库中:
```
import json
import pymysql
# 将list转换为json字符串
my_list = [1, 2, 3, 4]
json_str = json.dumps(my_list)
# 连接MySQL数据库
conn = pymysql.connect(host='localhost', port=3306, user='root', password='123456', db='test', charset='utf8mb4')
cursor = conn.cursor()
# 执行插入操作
sql = "INSERT INTO my_table (list_data) VALUES (%s)"
cursor.execute(sql, json_str)
conn.commit()
# 关闭连接
cursor.close()
conn.close()
```
在上面的代码中,我们将list [1,2,3,4] 转换为json字符串并存储到MySQL的my_table表中的list_data字段中。在插入操作时,使用%s占位符将json字符串作为参数传递给execute方法。注意,在执行插入操作之前,需要先将json字符串转换为字节数组,并设置MySQL连接的字符集为utf8mb4。