【问题标题】:Python MySQL insert and retrieve a list in BlobPython MySQL 在 Blob 中插入和检索列表
【发布时间】:2023-03-09 23:09:01
【问题描述】:

我正在尝试将元素列表插入 MySQL 数据库(插入 Blob 列)。这是我的代码示例:

myList = [1345,22,3,4,5]
myListString = str(myList)
myQuery = 'INSERT INTO table (blobData) VALUES (%s)'
cursor.execute(query, myListString)

一切正常,我的列表存储在我的数据库中。但是,当我想检索我的列表时,因为它现在是一个字符串,我不知道如何获取一个真正的整数列表而不是字符串。

例如,如果我现在这样做:

myQuery = 'SELECT blobData FROM db.table'
cursor.execute(myQuery)
myRetrievedList = cursor.fetch_all()
print myRetrievedList[0]

我会得到:

[

而不是:

1345

有什么方法可以将我的字符串 [1345,22,3,4,5] 转换为列表?

【问题讨论】:

    标签: python mysql string list blob


    【解决方案1】:

    您必须为您的列表选择一种数据格式,常见的解决方案按我的偏好排序:

    • json -- 快速、可读、允许嵌套数据,如果您的表曾经被任何其他系统使用,则非常有用。检查 blob 是否为有效格式。使用json.dumps()json.loads() 来转换字符串/blob 表示
    • repr() -- 快速、易读、适用于 Python 版本。如果有人进入您的数据库,则不安全。用户 repr()eval() 从字符串/blob 格式获取数据
    • pickle -- 快速,不可读,不能跨多个架构工作(afaik)。不检查 blob 是否被截断。使用cPickle.dumps(..., protocol=(cPickle.HIGHEST_PROTOCOL))cPickle.loads(...) 转换您的数据。

    【讨论】:

      【解决方案2】:

      根据此答案中的 cmets,OP 有一个作为 blob 字段输入的列表列表。在这种情况下,JSON 似乎是更好的选择。

      import json
      ...
      ...
      myRetrievedList = cursor.fetch_all()
      jsonOfBlob = json.loads(myRetrievedList)
      integerListOfLists = []
      for oneList in jsonOfBlob:
        listOfInts = [int(x) for x in oneList]
        integerListOfLists.append(listOfInts)
      
      return integerListOfLists #or print, or whatever
      

      【讨论】:

      • 您的解决方案看起来不错,但我有 1 个小问题。我撒谎让问题看起来更容易,实际上我有一个列表。所以 myList = [[1245, 22, 3, 4, 5] [1,2,3,4,5]]。那我该怎么办?
      猜你喜欢
      • 2018-06-08
      • 2013-03-26
      • 2012-05-08
      • 1970-01-01
      • 2021-01-05
      • 2016-11-28
      • 1970-01-01
      • 2012-08-30
      • 1970-01-01
      相关资源
      最近更新 更多