当我尝试将数据从SelectField添加到MySQL数据库时,发生此错误:
_mysql_exceptions.ProgrammingError _mysql_exceptions.ProgrammingError:并非在格式化字符串时转换了所有参数
我的代码:
class ContentForm(Form):
category = SelectField("Category: ",choices=[('DataScience','Data Science'), ('ComputerProgramming', 'Computer Programming'),('DigitalMarketing','Digital Marketing'),('Other','Other')], validators=[validators.DataRequired()])
title = StringField("Title: ",validators=[validators.length(min= 5, max = 100), validators.DataRequired()])
content = TextAreaField("Content: ", validators=[validators.length(min = 10), validators.DataRequired()])
@app.route("/addcontent", methods=["GET","POST"])
@login_required
def addcontent():
form = ContentForm(request.form)
if request.method == "POST" and form.validate():
category = form.category.data
title = form.title.data
content = form.content.data
cursor = mysql.connection.cursor()
query = "INSERT INTO contents (author, category, title,content) VALUES(%s,%s,%s)"
cursor.execute(query, (session["username"], category, title, content))
mysql.connection.commit()
cursor.close()
flash("Your content have added successfully. Thanks your contributions.", 'success')
return redirect(url_for("dashboard"))
return render_template("addcontent.html", form = form)
HTML:
{% from "includes/_formhelpers.html" import render_field %}
<form method="post">
{{ render_field(form.category, class="form-control", style = "width: 40% !important") }}
{{ render_field(form.title, class="form-control", style = "width: 40% !important") }}
{{ render_field(form.content, class="form-control", style = "height: 300px !important") }}
<button type="submit" class="btn btn-primary btn-lg">Add Content</button>
我该如何解决这个问题?
答案 0 :(得分:0)
您的问题来自
cursor.execute(query, (session["username"], category, title, content))
您应该以以下身份访问会话
session.get('username')
尝试使用一些字符串执行查询以进行测试以查看其是否将成功执行,例如:
cursor.execute(query, 'myName', category, title, content))