0
我使用python將SQL存儲在SQLite3數據庫中。當我將一些HTML插入到SQL表中時,如果有'''字符,就會出現錯誤/問題。SQL語句包含「或」的問題
我的問題下面的示例創建不正確的SQL語句:
INSERT INTO mytable(id, html, other) VALUE(1, " <img src="images/1.png" alt=""/> ", "some other info")
# it should be something like
INSERT INTO mytable(id, html, other) VALUE(1, " <img src=\"images/1.png\" alt=\"\"/> ", "some other info")
我怎麼能有「字符的SQL語句在它
import sqlite3
HTML = """ <img src="images/1.png" alt=""/> """ # NOTE the " characters in it
insert_qry = """ INSERT INTO mytable(id, html, other) VALUE(%s, "%s", "%s")"""
conn = sqlite3.connect(GlobalVars.db_path)
cur = conn.cursor()
res = cur.execute(insert_qry % (1, HTML, "some other info"))
# THESE FUNCTIONS DONT SOLVE MY PROBLEM:
def format_for_DB(src_code):
""" Post: """
src_code = src_code.replace('"', '\"')
src_code = src_code.replace("'", "\'")
return src_code
def format_for_display(src_code):
""" Post: """
src_code = src_code.replace('\"', '"')
src_code = src_code.replace("\'", "'")
return src_code
def format_for_DB(src_code):
""" Post: """
src_code = src_code.replace('"', '""')
src_code = src_code.replace("'", "''")
return src_code
def format_for_display(src_code):
""" Post: """
src_code = src_code.replace('""', '"')
src_code = src_code.replace("''", "'")
return src_code
如果答案是「** Always **用戶參數化查詢」,我們可以重複使用這個問題來解決許多類似的錯誤。 –