Python, MySQLdb and escaping table names?

前端 未结 3 1990
萌比男神i
萌比男神i 2020-12-11 17:13

I may be missing something obvious, but I can\'t figure out how my code is different from various examples I see in the online documentation for MySQLdb.

I\'m fairly

相关标签:
3条回答
  • 2020-12-11 18:03

    Interesting. But in the manual there are a couple of examples. Maybe it is something similar.

    c=db.cursor()
    max_price=5
    c.execute("""SELECT spam, eggs, sausage FROM breakfast
              WHERE price < %s""", (max_price,))
    

    In this example, max_price=5 Why, then, use %s in the string? Because MySQLdb will convert it to a SQL literal value, which is the string '5'. When it's finished, the query will actually say, "...WHERE price < 5".

    And

    c.executemany(
          """INSERT INTO breakfast (name, spam, eggs, sausage, price)
          VALUES (%s, %s, %s, %s, %s)""",
          [
          ("Spam and Sausage Lover's Plate", 5, 1, 8, 7.95 ),
          ("Not So Much Spam Plate", 3, 2, 0, 3.95 ),
          ("Don't Wany ANY SPAM! Plate", 0, 4, 3, 5.95 )
          ] )
    

    Here we are inserting three rows of five values. Notice that there is a mix of types (strings, ints, floats) though we still only use %s. And also note that we only included format strings for one row. MySQLdb picks those out and duplicates them for each row.

    0 讨论(0)
  • 2020-12-11 18:04

    MySQLdb is probably quoting your table names with single quotes instead of backticks. Try this

    cursor.execute('SELECT MAX(%%s) FROM `%s`' % table,(countcol))
    
    0 讨论(0)
  • 2020-12-11 18:05

    You cannot use DB-API for metadata; you will need to make replacements yourself outside of the execute() call.

    query = 'SELECT MAX(%%s) FROM `%s`' % (table,)
    cursor.execute(query, (countcol,))
    

    Obviously you should not do this if table comes from an outside source.

    0 讨论(0)
提交回复
热议问题