开发者

Problem having SQL statements that contain " or '

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( '"', '""' )
  开发者_C百科  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


Use a parameterized query:

query =  """ INSERT INTO mytable(id, html, other) VALUES(?, ?, ?) """

# ...

cur.execute(query, (1, HTML, "some other info"))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜