将未知数插入SQLite数据库

时间:2012-12-19 06:38:07

标签: python string sqlite python-2.7

  

可能重复:
  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))

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

1 个答案:

答案 0 :(得分:2)

永远不要使用字符串格式来创建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))

请参阅execute的{​​{3}}。

相关问题