【问题标题】:What data type is used for saving lists in sqlite3 using Python?什么数据类型用于使用 Python 在 sqlite3 中保存列表?
【发布时间】:2021-07-06 09:07:26
【问题描述】:

据我所知,一个 sqlite3 表中只有五种数据类型可以设置为列。它们是:

  • null 表示没有数据。
  • integer 表示整数。
  • real 表示浮点数。
  • text 表示任何字符串。
  • blob 一个二进制数据字段,您可以在其中存储文件、文档、图像。

但目前,我的代码中有一个名为 self. inventory 的列表,当用户执行特定操作时,它会偶尔将项目添加到其中。这不是问题。我的问题是我应该为要存储在表中的列表分配什么数据类型?或者有没有其他方法可以用来将表的值存储到数据库中。目前,这是我的连接、游标和表执行:

connection = sqlite3.connect('db_of_game.db')
cursor = connection.cursor()

cursor.execute(
    'CREATE TABLE user_data(user_name text primary key, money integer, inventory <What data type to use here?>, deposited integer, allowed_deposit integer)'
    )

connection.commit()
connection.close()

【问题讨论】:

  • 您可以将列表项连接成逗号分隔的字符串 ("item1,item2,item3") 并使用 text 类型,然后在从数据库中读取时使用 .split(",") 获取列表。跨度>
  • 我是否创建一个包含逗号分隔字符串的变量并将其添加到表中?这是最好的方法吗?如何在需要时将其重新添加到列表中?
  • 是的,创建一个变量是个好主意。这可能是最好的方法,当然也是最简单的。要将其带回列表,请使用list.split(",")。这会将逗号分隔的字符串转换为 python 列表。
  • 永远不要在表格中存储逗号分隔的字符串。阅读:stackoverflow.com/questions/3653462/…
  • 那我该怎么办? @forpas

标签: python-3.x list sqlite


【解决方案1】:

假设每个项目只能属于一个用户,您将使用一对多模式。许多项目,一个用户。项目有自己的表,它们引用它们的用户。

create items (
  id integer primary key,
  name text not null,
  user_name text not null references user_data(user_name)
)

(注意:应避免使用用户名作为主键。用户名更改。主键无法更改。它们还需要更多的存储和比较时间。相反,请使用简单的整数。In SQLite integer primary key works。)

然后获取所有用户的物品...

select items.name
from items
where user_name = ?

如果每个项目可以属于多个用户,那就是多对多关系,您需要一个连接表来将用户链接到项目。

create items (
  id integer primary key,
  name text not null
)

create inventory (
  item_id integer not null references items(id),
  user_name text not null references user_data(user_name)
)

要获取用户的库存,您可以检查库存以获取项目 ID,并与项目连接以获取项目名称。

select items.name
from items
join inventory on items.id = inventory.item_id
where inventory.user_name = ?

这可能看起来很复杂,但这就是关系数据库的工作方式。通过建立项目之间的关系。绕着你的脑袋要花点时间,但这是值得的。它使搜索速度非常快。如果您使用逗号分隔列表并希望找到具有特定项目的用户,则需要查看每个用户并解析他们的列表。现在您只需查询 items 表。如果items.nameindexed,则不必搜索整个表。

select *
from items
where item.name like ?

更多...

【讨论】:

    猜你喜欢
    • 2012-03-27
    • 1970-01-01
    • 2011-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-01
    • 1970-01-01
    相关资源
    最近更新 更多