![](/img/trans.png)
[英]ProgrammingError: Wrong number of arguments during string formatting
[英]ProgrammingError: Wrong number of arguments during string formatting, tried tuple fix
因此,在創建表,然后調用 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
可以用作查詢中的占位符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.