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)
);
我要做的是将sessionStorage中的所有数据保存到MySQL服务器中。我有上面的代码,并且发生的错误是 500内部错误。我已经尝试创建表以包含所有VARCHAR字段类型但它们仍然不起作用。我认为错误可能发生在app.py中但不确定如何修复它。
答案 0 :(得分:0)
使用flask_mysqldb插入数据您需要使用以下格式的SQL语句:
func2
然后,
sql = 'INSERT INTO data_table (age, gender, name, email, accuracy) VALUES (%d, %d, %s, %s, %f)'