在python中調(diào)用MySQLdb模塊插入數(shù)據(jù)信息,假設(shè)待輸入信息data為:
其中同時包含了單引號和雙引號
一般插入語句為
sql = "insert into tb (my_str) values('%s')" % (data)
cursor.execute(sql)</pre>
其中values('%s')中的%s外面也要有引號,這個引號與data中的引號匹配導(dǎo)致了內(nèi)容錯誤
解決辦法一: MySQLdb.escape_string()
在MySQLdb模塊中自帶針對mysql的轉(zhuǎn)義函數(shù)escape_string(),直接調(diào)用即可
sql = "insert into tb (my_str) values('%s')" % (MySQLdb.escape_string(data))
cursor.execute(sql)
解決辦法二:轉(zhuǎn)義字符
將data變?yōu)橄旅娴男问?再插入數(shù)據(jù)庫就正確了
Hello\'World\"!
具體在python中的轉(zhuǎn)義函數(shù)如下:
def transferContent(self, content):
if content is None: return None else:
string = ""
for c in content: if c == '"':
string += '\\\"'
elif c == "'":
string += "\\\'"
elif c == "\\":
string += "\\\\"
else:
string += c return string</pre>