Passing a column name in a SELECT statement in Python

后端 未结 2 377
忘了有多久
忘了有多久 2020-11-29 13:48
    if count == 1:
        cursor.execute(\"SELECT * FROM PacketManager WHERE ? = ?\", filters[0], parameters[0])
        all_rows = cursor.fetchall()

    elif coun         


        
相关标签:
2条回答
  • 2020-11-29 14:19

    You cannot use SQL parameters to interpolate column names. You'll have to use classic string formatting for those parts. That's the point of SQL parameters; they quote values so they cannot possibly be interpreted as SQL statements or object names.

    The following, using string formatting for the column name works, but be 100% certain that the filters[0] value doesn't come from user input:

    cursor.execute("SELECT * FROM PacketManager WHERE {} = ?".format(filters[0]), (parameters[0],))
    

    You probably want to validate the column name against a set of permissible column names, to ensure no injection can take place.

    0 讨论(0)
  • 2020-11-29 14:35

    You can only set parameters using ?, not table or column names.

    You could build a dict with predefined queries.

    queries = {
        "foo": "SELECT * FROM PacketManager WHERE foo = ?",
        "bar": "SELECT * FROM PacketManager WHERE bar = ?",
        "foo_bar": "SELECT * FROM PacketManager WHERE foo = ? AND bar = ?",
    }
    
    # count == 1
    cursor.execute(queries[filters[0], parameters[0])
    
    # count == 2
    cursor.execute(queries[filters[0] + "_" + queries[filters[1], parameters[0])
    

    This approach will make you save from SQL injection in filters[0].

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