Summary : Python3 can use PyMysql to read and write MySQL database, but when assembling sql, the quotation marks in the string may cause sql syntax errors. This problem can be solved perfectly by Hex.
Original way : because of the single quotes in str_value, the assembled sql will have grammatical errors
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()
Alternative : After converting str_value to a hex string, use MySQL's unhex() function to decode it, which can perfectly solve the problem of quotation marks
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()