0

I am trying to save a file as a BLOB in a MySQL database. The DB is very simple right now, a table with One column "File" as type longblob.

The code is as follows:

file = open("file.txt","r")
data = file.readlines()
dp = pickle.dumps(data,1)
sql = "insert into Files values (%s)"
cursor.execute(sql,(MySQLdb.escape_string(dp),))

This seems to upload fine, however when retrieving the data, I get an EOFError when trying to unpickle. If I try the process without pickling at all, the string is not unescaped and the escape characters stay in the string when written back to the file (unless there is a python step I am missing there to unescape/re-escape).

sql = "select File from Files"
cursor.execute(sql)
ret = cursor.fetchone()
pickle.loads(ret[0])

EOFError exception
4

2 回答 2

0

我不确定为什么腌制列表没有正确取消腌制,但我能够通过将 readlines 列表加入字符串并将其作为长文本类型上传到 MySQL 来解决这个问题。

于 2013-08-26T14:47:40.040 回答
0

您不应同时使用 MySQLdb.escape_string 和参数样式 sql。这些将起作用:

1、

sql = "insert into Files values (%s)"
cursor.execute(sql,(dp,))

2、

sql = "insert into Files values ('{}')".format(MySQLdb.escape_string(dp))
cursor.execute(sql)
于 2017-09-26T07:34:06.867 回答