我想将包含二进制数据的字符串对象插入到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)
Run Code Online (Sandbox Code Playgroud)
结果(但不是每次......)
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")
Run Code Online (Sandbox Code Playgroud)
这个问题显然归结为MySQL不喜欢的二进制数据中的某些字符.是否存在将二进制数据放入MySQL数据库的故障安全方法?
这样做,相反:
query = '''INSERT INTO cheese (data) VALUES (%s)'''
cur.execute(query, (bd,))
Run Code Online (Sandbox Code Playgroud)
这不使用Python级别的字符串格式,而是使用特定于MySQL的格式,包括在嵌入查询的字符串中转义对MySQL具有特殊含义的字符.
| 归档时间: |
|
| 查看次数: |
6646 次 |
| 最近记录: |