概要:Python3 中可以使用 PyMysql 来读写 MySQL 数据库,但是在拼装 sql 的时候,可能会因为字符串中的引号导致 sql 语法错误,通过 Hex 的方式可以完美解决该问题。
原始方式:因为 str_value 中的单引号,会导致拼装出来的 sql 出现语法错误
str_value = "12'3'456"
sql = "insert into test_table(str_value) values('%s')" % (str_value)
with conn.cursor() as cursor:
cursor.execute(sql)
conn.commit()
替换方案:把 str_value 转换为 hex 串后,再利用 MySQL 的 unhex() 函数来解码,可以完美解决引号问题
str_value = "12'3'456"
sql = "insert into test_table(str_value) values(unhex('%s'))" % (str_value.encode().hex())
with conn.cursor() as cursor:
cursor.execute(sql)
conn.commit()
本文介绍在Python3中使用PyMysql操作MySQL数据库时,如何通过将字符串转换为Hex格式,再利用MySQL的unhex()函数解码,巧妙解决因字符串内含引号导致的SQL语法错误。

843

被折叠的 条评论
为什么被折叠?



