我无法使用mysql和flask在我的数据库中更新或插入值,而且运行它时我的代码没有错误

问题描述

很抱歉,问题很长,请查看功能寄存器,我只能访问数据库中存在的值,但我无法使用此功能插入值,请仔细查看此问题

此外,尝试注册时我没有任何错误

from flask import Flask,render_template,request,redirect,url_for,session
from flask_MysqLdb import MysqL
import MysqLdb.cursors
import re

app=Flask(__name__)

app.secret_key = 'your secret key'
app.config['MysqL_HOST'] = 'localhost'
app.config['MysqL_USER'] = 'root'
app.config['MysqL_PASSWORD'] = 'nfjkngk'
app.config['MysqL_DB'] = 'test'

MysqL = MysqL(app)




@app.route('/register',methods =['GET','POST'])
def register():
    msg = ''
    if request.method == 'POST' and 'mail_id' in request.form and 'passwd' in request.form and 'P_name' in request.form and 'age' in request.form and 'blood_group' in request.form and 'sex' in request.form :
        conn=MysqL.connect
        cursor=conn.cursor()
        mail_id = request.form['mail_id']
        passwd = request.form['passwd']
        P_name = request.form['P_name']
        age = request.form['age']
        blood_group = request.form['blood_group']
        sex=request.form['sex']
        cursor.execute('SELECT * FROM patient WHERE mail_id = % s',(mail_id,))
        patient = cursor.fetchone()
        if patient:
            msg = 'Account already exists !'
        elif not re.match(r'[^@]+@[^@]+\.[^@]+',mail_id):
            msg = 'Invalid email address !'
        else:
            cursor.execute('INSERT INTO patient VALUES (NULL,% s,% s)',passwd,P_name,age,blood_group,sex,))
            conn.commit()
            msg = 'You have successfully registered !'
            return redirect(url_for('index.html'))
    else:
        msg = 'Please fill out the form !'
    return render_template('register.html',msg = msg)

@app.route("/index")
def index():
    if 'loggedin' in session:
        return render_template("index.html")
    return redirect(url_for('login'))


if __name__ == "__main__":
    app.debug=True
    app.run(host ="localhost",port = int("5000"))

解决方法

准备好flask_sql documentation之后,我可以清楚地看到flask_sql才刚刚进入开发的初始阶段,还不够成熟,无法推荐用于开发。因此,为了获得更好的结果,我将推荐sqlAlchemy或MySQLdb

唯一似乎出错的是代码中的以下语句:

 cursor.execute('INSERT INTO patient VALUES (NULL,% s,% s)',(mail_id,passwd,P_name,age,blood_group,sex,))
 

以上语句的正确版本将没有%空间s,并且包括index_id:

 cursor.execute('INSERT INTO patient VALUES (%d,%s,%s)',(index_id,mail_id,))
 

这些不是语法错误,所以这就是为什么您没有收到错误。

,

如果您使用 SQLAlchemy ,这可能很容易,因为它最适合烧瓶并且易于使用