if count == 1: cursor.execute("SELECT * FROM PacketManager WHERE ? = ?", filters[0], parameters[0]) all_rows = cursor.fetchall() elif count == 2: cursor.execute("SELECT * FROM PacketManager WHERE ? = ? AND ? = ?", filters[0], parameters[0],
if count == 1: cursor.execute("SELECT * FROM PacketManager WHERE ? = ?", filters[0], parameters[0]) all_rows = cursor.fetchall() elif count == 2: cursor.execute("SELECT * FROM PacketManager WHERE ? = ? AND ? = ?", filters[0], parameters[0], filters[1], parameters[1]) all_rows = cursor.fetchall() elif count == 3 : cursor.execute("SELECT * FROM PacketManager WHERE ? = ? AND ? = ? AND ? = ?", filters[0], parameters[0], filters[1], parameters[1], filters[2], parameters[2]) all_rows = cursor.fetchall()
这是我程序中的代码段.我打算做的是在查询中传递列名和参数.
filters数组包含列名,参数数组包含参数.计数是用户设置的过滤器数量.过滤器和参数数组已准备就绪,没有问题.我只需要将它传递给查询即可执行.这给我一个错误“TypeError:函数最多需要2个参数”
您只能使用?而不是表名或列名来设置参数.您可以使用预定义的查询构建一个dict.
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])
这种方法将使您从过滤器[0]中的SQL注入中保存.