【问题标题】:Inserting Unknowns into SQLite Database [duplicate]将未知数插入 SQLite 数据库 [重复]
【发布时间】:2012-12-06 11:26:50
【问题描述】:

可能重复:
Passing SQLite variables in Python

我的脚本中有一个函数将值传递给一个类方法,该方法的工作是用它接收到的变量填充其分配的数据库。问题是,我不确定语法是否正确,因为我没有使用普通字符串。方法如下。

def new_response(self, link_pattern, link, response, ref_id=""):
    self.db_cursor.execute('''INSERT INTO tb_memory VALUES 
    (%s, %s, %s, %s)''' % (ref_id, link_pattern, link, response))

什么是最合适的句法方法?

【问题讨论】:

    标签: python string sqlite python-2.7


    【解决方案1】:

    永远不要使用字符串格式来创建 SQL 语句!如果您使用字符串格式化,您的程序将受到可能的 SQL 注入攻击的影响。 使用'?' 占位符:

    def new_response(self, link_pattern, link, response, ref_id=""):
        self.db_cursor.execute('''INSERT INTO tb_memory VALUES 
        (?, ?, ?, ?)''', (ref_id, link_pattern, link, response))
    

    请参阅documentation 以获取execute

    【讨论】:

    • 也许请注意,None 在此处作为参数传递时将被视为NULL(未知)值:这就是问题所在。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-17
    • 1970-01-01
    相关资源
    最近更新 更多