您好我使用以下代码将下面的html页面中输入的值保存到MySQL DB。添加了下拉列表“RequestType”,但是当从“RequestType”中选择值并点击提交按钮时遇到以下错误。放置了Flask和HTML中使用的代码。请求您的帮助以解决此问题。
TypeError:execute()需要2到3个位置参数,但是给出了5个
Basic html page with three values i.e. name, email and Request Type
Flask中使用的代码如下
from flask import Flask, render_template, request, redirect
from flask_mysqldb import MySQL
app = Flask(__name__)
# Configure db
#db = yaml.load(open('db.yaml'))
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
#app.config['MYSQL_PASSWORD'] = 'P@$$w0rd'
app.config['MYSQL_DB'] = 'flaskapp'
mysql = MySQL(app)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
# Fetch form data
userDetails = request.form
name = userDetails['name']
email = userDetails['email']
requesttype = userDetails.get('requesttype')
cur = mysql.connection.cursor()
cur.execute("INSERT INTO users(name, email, requesttype) VALUES(%s, %s, [])", name, email, requesttype)
mysql.connection.commit()
cur.close()
return 'Save is Successful'
return render_template('index.html')
HTML代码如下。
<form method="POST" action="{{ url_for('index') }}">
Name <input type="text" name="name" />
<br>
Email <input type="email" name="email" />
<br>
RequestType <select id="RequestType" name = "RequestType" >
<option selected value="1">New</option>
<option value="0">Old</option>
</select><br>
<input type="Submit">
</form>
答案 0 :(得分:0)
以下内容应该有效
def index():
if request.method == 'POST':
# Fetch form data
userDetails = request.form
name = userDetails['name']
email = userDetails['email']
requesttype = userDetails['RequestType']
cur = mysql.connection.cursor()
cur.execute("""INSERT INTO users (name, email, requesttype) VALUES (%s, %s, %s)""", (name, email, requesttype))
mysql.connection.commit()
cur.close()
return 'Save is Successful'
return render_template('index.html')
三重引号将阻止您在MySQL中出现任何语法错误。另请注意(name, email, requesttype)
处添加的括号。