编程错误:格式化字符串时参数数量错误,已尝试修复元组



因此,在创建一个表,然后调用insert into之后,我在设置字符串格式时收到一个错误,说参数数量不对。我试着查找这个问题,上面写着让第二个参数成为元组,但我没有成功。不知道为什么我仍然会出现这个错误。我是的变量的值

创建功能:

table_ddl = "CREATE TABLE movies (id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255), year VARCHAR(255), director VARCHAR(255), actor VARCHAR(255), release_date VARCHAR(255), rating VARCHAR(255))"
cnx = ''
try:
cnx = mysql.connector.connect(user=username, password=password,
host=hostname,
database=db)
except Exception as exp:
print(exp)
import MySQLdb
#try:
cnx = MySQLdb.connect(unix_socket=hostname, user=username, passwd=password, db=db)
#except Exception as exp1:
#    print(exp1)
cur = cnx.cursor()
try:
cur.execute(table_ddl)
cnx.commit()
populate_data()
except mysql.connector.Error as err:
if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:
print("already exists.")
else:
print(err.msg)

插入函数:标题、年份等取自html请求

def add_to_db():
print("Received request.")
title = request.form['title']
year = request.form['year']
director = request.form['director']
actor = request.form['actor']
release_date = request.form['release_date']
rating = request.form['rating']
db, username, password, hostname = get_db_creds()
cnx = ''
try:
cnx = mysql.connector.connect(user=username, password=password,
host=hostname,
database=db)
except Exception as exp:
print(exp)
import MySQLdb
cnx = MySQLdb.connect(unix_socket=hostname, user=username, passwd=password, db=db)
cur = cnx.cursor()
sql = "INSERT INTO movies (title,year,director,actor,release_date,rating) VALUES (%s,%d,%s,%s,%s,%f)"
val = [title,year,actor,director,release_date,rating]
cur.execute(sql,val) # line with error
cnx.commit()
return hello()

HTML代码

<form action="add_to_db" method="post">
<h4>Insert Movie</h4>
<br>
Year: <input type="text" name="year"><br>
Title: <input type="text" name="title"><br>
Director: <input type="text" name="director"><br>
Actor: <input type="text" name="actor"><br>
Release Date: <input type="text" name="release_date"><br>
Rating: <input type="text" name="rating"><br>
<input type="submit" value="Insert Movie">
</form>

cursor.execute()使用的占位符不是通用的%格式运算符。只能使用%s,不能使用%d%f。就cursor.execute()而言,您只为6个参数提供了4个占位符。

所以应该是:

sql = "INSERT INTO movies (title,year,director,actor,release_date,rating) VALUES (%s,%s,%s,%s,%s,%s)"

来自文件:

如果args是列表或元组,则%s可以用作查询中的占位符。如果args是dict,则%(name)s可以用作查询中的占位符。

最新更新