2017-12-27 269 views
-3

我正在開發一個Web應用程序使用Flask。在某些時候,我必須插入某些HTML腳本到MySQL數據庫:插入HTML到MySQL數據庫顯示類型錯誤

<h3>Welcome!</h3> 
<p>Some text</p> 

當我將其插入到數據庫中(當它被瓶中的「render_template」函數返回):

\n\n<h3>Welcome!</h3>\n\n\n\n<p>Some text</p> 

我得到以下錯誤:

TypeError: ProgrammingError(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '\\\\\\\\n\\\\n<h3>Welcome!</h3>\\\\n\\\\n\\\\n\\\\n<p>Some text' at line 1") is not JSON serializable

我第一次不明白什麼JSON序列化「的意思,我想知道我做錯了。我已經嘗試脫線(\n),但它仍然顯示相同的錯誤。爲什麼?我很感謝你能提供的任何答案。

+0

where is SQL query? – furas

回答

0

編寫HTML時數據庫通常用於甲解決方案:

1)簡單地轉換數據庫字段類型成團塊這樣它將接受二進制數據,然後編碼HTML爲二進制(下面例子)。 2)將數據庫字段保留爲文本字段,但base64對數據進行編碼,以便數據庫不會抱怨非法字符。

# Example for case 1. 
# Note that you need to make sure the database field is a blob: 
html = '<h3>Welcome!</h3>\n<p>Some text</p>' 
bin = html.encode() 
dbhandle.execute('INSERT INTO script (various fields, binhtml) VALUES (..., bin)') 
# When you read back the data, remember to decode. 
dbhandle.execute('SELECT binhtml FROM script WHERE...') 
resultset = dbhandle.fetchall() 
htmlresult = resultset.decode() 

# Example for case 2. 
# Database field can be a text/varchar type because base64 ensures it will work. 
import base64 
html = '<h3>Welcome!</h3>\n<p>Some text</p>' 
# Convert HTML into base64 encoded *text* so it can be stored in text field. 
encoded = base64.b64decode(html.encode()).decode() 
# Do the database INSERT. 
... 
# Retrieve the stored text from the database and convert back to HTML 
dbhandle.execute('SELECT encodedhtml FROM script WHERE...') 
resultset = dbhandle.fetchall() 
htmlresult = base64.b64decode(resultset).decode()