Reputation: 117
The following code is asking the system to enter each checkbox that has been filled in, and then displayed. The display page is actually displaying the new registered rows, but when I make the same code SELECT * FROM at my terminal, the system does not show any. It looks like the database is temporary, because when i restart the flask app, the new rows disappear.
from flask import Flask, render_template, request
import pymysql
db = pymysql.connect("127.0.0.1", "root", "toor", "msg_test")
app = Flask(__name__)
app.config['SECRET_KEY'] = '31e1326344483068'
@app.route('/preenche', methods=['POST'])
def selecionarExames():
if request.method == 'POST':
cursor = db.cursor()
for t in request.form.getlist('check'):
sql = "INSERT INTO exames_realizados (nomeExame, valores) VALUES ('{}', 0)".format(t)
cursor.execute(sql)
v = "SELECT * FROM exames_realizados"
cursor.execute(v)
results = cursor.fetchall()
return render_template('preenche.html', results=results)
if __name__ == '__main__':
app.run(debug=True)
Upvotes: 0
Views: 2028
Reputation: 473873
First of all, do not string format your query - you are opening up your code to SQL injection attacks. Instead, properly parameterize your query:
sql = """
INSERT INTO
exames_realizados
(nomeExame, valores)
VALUES
(%s, 0)
"""
cursor.executemany(sql, request.form.getlist('check'))
Note how the query parameters are passed separately and the use of .executemany()
.
As far as seeing the results of your insert query, commit your transaction to persist the changes:
db.commit()
Upvotes: 2