Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python MySQL在Blob中插入和检索列表_Python_Mysql_String_List_Blob - Fatal编程技术网

Python MySQL在Blob中插入和检索列表

Python MySQL在Blob中插入和检索列表,python,mysql,string,list,blob,Python,Mysql,String,List,Blob,我试图将元素列表插入MySQL数据库(一个Blob列)。以下是我的代码示例: myList = [1345,22,3,4,5] myListString = str(myList) myQuery = 'INSERT INTO table (blobData) VALUES (%s)' cursor.execute(query, myListString) 一切正常,我的列表存储在数据库中。但是,当我想要检索我的列表时,因为它现在是一个字符串,我不知道如何得到一个真正的整数列表而不是字符串 例

我试图将元素列表插入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]转换成一个列表?

根据这个答案中的注释,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

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

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

您的解决方案看起来不错,但我有一个小问题。我撒谎是为了让问题看起来更简单,事实上我有一张清单。所以myList=[[1245,22,3,4,5][1,2,3,4,5]]。那我该怎么办?