SQL语句包含“或”的问题

时间:2011-09-24 00:06:46

标签: python sql sqlite syntax

我使用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

1 个答案:

答案 0 :(得分:3)

使用参数化查询:

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

# ...

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