插入HTML到MySQL数据库显示类型错误

weixin_38073436 2019-09-12 03:40:16

我正在开发一个Web应用程序使用Flask。在某些时候,我必须插入某些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),但它仍然显示相同的错误。为什么?我很感谢你能提供的任何答案。








...全文
69 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
weixin_38112805 2019-09-12
  • 打赏
  • 举报
回复

编写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()

435

社区成员

发帖
与我相关
我的任务
社区描述
其他技术讨论专区
其他 技术论坛(原bbs)
社区管理员
  • 其他技术讨论专区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧