Heim  >  Fragen und Antworten  >  Hauptteil

Wie verwende ich Variablen in SQL-Anweisungen in Python?

<p>Ich habe den folgenden Python-Code: </p> <pre class="brush:py;toolbar:false;">cursor.execute("INSERT INTO table VALUES var1, var2, var3,") </pre> <p>Wobei <code>var1</code> eine Ganzzahl ist, sind <code>var2</code> und <code>var3</code> </p> <p>Wie schreibe ich Variablennamen in Python, ohne dass sie im Abfragetext enthalten sind? </p>
P粉200138510P粉200138510426 Tage vor471

Antworte allen(2)Ich werde antworten

  • P粉545682500

    P粉5456825002023-08-21 13:22:44

    Python DB-API的不同实现允许使用不同的占位符,所以你需要找出你正在使用的是哪个 -- 例如(使用MySQLdb):

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

    或者(使用Python标准库中的sqlite3):

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

    或者其他的(在VALUES之后你可以有(:1, :2, :3),或者"命名样式"(:fee, :fie, :fo)或者(%(fee)s, %(fie)s, %(fo)s),在execute的第二个参数中传递一个字典而不是一个映射)。检查你正在使用的DB API模块中的paramstyle字符串常量,并在http://www.python.org/dev/peps/pep-0249/上查找paramstyle,以了解所有的参数传递样式!

    Antwort
    0
  • P粉926174288

    P粉9261742882023-08-21 10:38:41

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

    请注意参数被传递为一个元组,(a, b, c)。如果你只传递一个参数,元组需要以逗号结尾,(a,)

    数据库API会对变量进行适当的转义和引用。请注意不要使用字符串格式化运算符(%),因为

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

    Antwort
    0
  • StornierenAntwort