使用Flask Mysqldb通过AJAX将行插入数据库 [英] Using Flask Mysqldb to insert rows into database with AJAX

查看:184
本文介绍了使用Flask Mysqldb通过AJAX将行插入数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 Internal Error .我尝试创建具有所有VARCHAR字段类型的表,但它们仍无法正常工作.我认为该错误可能发生在app.py中,但不确定如何解决.

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.

推荐答案

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

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)'

然后

cur.execute(sql, (age, gender, name, email, accuracy))
mysql.connection.commit()

这篇关于使用Flask Mysqldb通过AJAX将行插入数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆