问题
So i use flask_mysqldb in a Flask(Python website)
I'm trying to write a function to delete a row in any table. It works perfectly when I hardcode the tablename, but what do I need to do to be able to use a variable instead?
@app.route('/delete/<string:table>/<string:id>', methods=['POST'])
@is_logged_in
def delete(table, id):
# Create Cursor
cur = mysql.connection.cursor()
# Execute
cur.execute("DELETE FROM %s WHERE id = %s", (table, id))
mysql.connection.commit()
cur.close()
flash('%s deleted'(table), 'success')
return redirect(url_for('dashboard'))
回答1:
cur.execute("DELETE FROM %s WHERE id = %s", (table, id))
should be
cur.execute("DELETE FROM %s WHERE id = %s" % (table, id))
来源:https://stackoverflow.com/questions/48024806/flask-mysqldb-delete-from-variable-table