SQL 语句包含“”时出现问题或'
我使用 python 将 HTML 存储在 SQLite3 数据库中。当我将一些 HTML 插入到 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
I am storing HTML in an SQLite3 database using python. When I go to insert some HTML into an SQL table I get an error/problem when I have '"' characters.
The following example of my problem creates the incorrect SQL statement:
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")
How can I have an SQL statement with " characters in it?
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用参数化查询:
Use a parameterized query: