[英]Creating an insert query with escape characters in MySQL/Python
我正在編寫一個將數據從 Access 數據庫傳輸到 MySQL 數據庫的腳本。 我正在嘗試生成類似於以下的查詢:
INSERT into customers (firstname, lastname) value ('Charlie', "D'Amelio");
但是,MySQL 不喜歡上面列出的雙引號。 我編寫了一個笨重的函數來嘗試用 ' 替換 D'Amelio 中的 '。 下面是創建 SQL 語句的整個函數:
def dictionary_output(dict):
output = "INSERT into lefm_customers "
fields = "(id, "
vl = "('" + id_gen() + "', "
for key in dict.keys():
# print(dict[key])
if str(dict[key]) == 'None' or str(dict[key]) == "":
pass
elif "'" in str(dict[key]):
fields = fields + str(key) + ", "
string = ""
for character in string:
if character == "'":
string += r"\'"
else:
string += character
vl = "'" + string + "', "
else:
fields = fields + str(key) + ", "
vl = vl + "'" + str(dict[key]) + "', "
fields = fields[:-2] + ")"
vl = vl[:-2] + ");"
return "INSERT into lefm_customers " + fields + " values " + vl
目前它只是完全忽略了這個價值。 關於用什么替換 ' 或如何改進我的功能的任何提示? 謝謝!
這修復了它:
def dictionary_output(dict):
lst = []
output = "INSERT into lefm_customers "
fields = "(id, "
vl = "('" + id_gen() + "', "
for key in dict.keys():
# print(dict[key])
if str(dict[key]) == 'None' or str(dict[key]) == "":
pass
else:
fields = fields + str(key) + ", "
vl = vl + "%s, "
lst.append(dict[key])
fields = fields[:-2] + ")"
vl = vl[:-2] + ");"
return ("INSERT into lefm_customers " + fields + " values " + vl, lst)
for name in access_dict:
if str(name) not in mysql_dict.keys():
try:
statement = dictionary_output(access_dict[name])
mysql_cursor.execute(statement[0], statement[1])
print('attempting ' + str(name))
db_connection.commit()
print("Success!")
except:
print('something went wrong')
你可以只調用 Python 的替換。 終端中的示例:
>>> s = "D'Amelio"
>>> s.replace("'", "'")
"D'Amelio"
在這種情況下,第一個參數是單引號 ',第二個參數是重音 '。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.