问题
JQUERY
var localdata = new Object(); // JSON dict
for (var i = 0; i < sessionStorage.length; ++i) {
localdata[sessionStorage.key(i)] = sessionStorage.getItem(sessionStorage.key(i));
}
$.ajax({
url: "{{ url_for('save', _external=True) }}", // Function to send data
type: "POST",
dataType: "json",
contentType: "application/json; charset=UTF-8",
accepts: {
json: "application/json"
},
data: JSON.stringify(localdata),
success: function(data) {
window.location.replace("/quit"); // Redirect to another page after saving data
}
});
app.py
from flask_mysqldb import MySQL
app = Flask(__name__)
app.config["MYSQL_HOST"] = "localhost"
app.config["MYSQL_USER"] = "root"
app.config["MYSQL_PASSWORD"] = "password"
app.config["MYSQL_DB"] = "somedb"
mysql = MySQL(app)
@app.route("/save", methods=["POST"])
def save():
cur = mysql.connection.cursor()
json_dict = request.get_json()
age = int(json_dict["Age"])
gender = int(json_dict["Gender"])
name = str(json_dict["Name"])
email = str(json_dict["Email"])
accuracy = float(json_dict["Accuracy"])
fields = (age, gender, email, accuracy)
sql = """INSERT INTO data_table (age, gender, name, email, accuracy) VALUES (%d, %d, %s, %s, %f);"""
cur.execute(sql % fields)
mysql.connection.commit()
MySQL
CREATE TABLE data_table (
SubjectId INT NOT NULL AUTO_INCREMENT,
Age TINYINT,
Gender TINYINT,
Name VARCHAR(100),
Email VARCHAR(255),
Accuracy FLOAT,
PRIMARY KEY (SubjectId)
);
What I'm trying to do is to save all the data in the sessionStorage into the MySQL server. I have the above code and the error that kept occurring was a 500 Internal Error. I have tried creating the table to have all VARCHAR field types as well but they do not work still. I'm thinking the error might have occurred in app.py but not sure how to fix it.
回答1:
To insert data using flask_mysqldb You need to have your SQL statement in following format:
sql = 'INSERT INTO data_table (age, gender, name, email, accuracy) VALUES (%d, %d, %s, %s, %f)'
Then,
cur.execute(sql, (age, gender, name, email, accuracy))
mysql.connection.commit()
来源:https://stackoverflow.com/questions/39411383/using-flask-mysqldb-to-insert-rows-into-database-with-ajax