繁体   English   中英

在MySQL blob中插入python二进制字符串对象

[英]Insert python binary string object in MySQL blob

我想将包含二进制数据的字符串对象插入到MySQL blob列中。 但是,我不断收到MySQL语法错误。

我为调试目的制作了一个小脚本:

import MySQLdb
import array
import random

conn = MySQLdb.connect(host="localhost", user="u", passwd="p", db="cheese")
cur = conn.cursor()

a = array.array('f')
for n in range(1,5):
    a.append(random.random())
bd = a.tostring()
print type(bd) # gives str
query = '''INSERT INTO cheese (data) VALUES (%s)''' % bd
cur.execute(query)

结果(但不是每次......)

ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near '?fJ\x95<=  
\xad9>\xf3\xec\xe5>)' at line 1")

这个问题显然归结为MySQL不喜欢的二进制数据中的某些字符。 是否存在将二进制数据放入MySQL数据库的故障安全方法?

这样做,相反:

query = '''INSERT INTO cheese (data) VALUES (%s)'''
cur.execute(query, (bd,))

这不使用Python级别的字符串格式,而是使用特定于MySQL的格式,包括在嵌入查询的字符串中转义对MySQL具有特殊含义的字符。

该错误与字符串的格式化无关,而与SQL语法有关。 所以我猜问题是SQL查询本身,而不是字符。 使用query = '''INSERT INTO cheese (data) VALUES ('%s')''' % bd将所讨论的字符串括在单引号中的位置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM