1

查询

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
    }
});

应用程序.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 Internal Error。我已经尝试创建表以包含所有 VARCHAR 字段类型,但它们仍然无法正常工作。我认为该错误可能发生在 app.py 中,但不知道如何修复它。

4

1 回答 1

2

要使用 flask_mysqldb 插入数据,您需要使用以下格式的 SQL 语句:

sql = 'INSERT INTO data_table (age, gender, name, email, accuracy) VALUES (%d, %d, %s, %s, %f)'

然后,

cur.execute(sql, (age, gender, name, email, accuracy))
mysql.connection.commit()
于 2018-03-14T08:01:53.083 回答