且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Python 中的 SQL 语句中使用变量?

更新时间:2023-01-19 17:02:38

cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3))

注意参数是作为元组传递的.

Note that the parameters are passed as a tuple.

数据库 API 会正确地转义和引用变量.注意不要使用字符串格式化操作符 (%),因为

The database API does proper escaping and quoting of variables. Be careful not to use the string formatting operator (%), because

  1. 它不做任何转义或引用.
  2. 它容易受到不受控制的字符串格式攻击,例如SQL 注入.