繁体   English   中英

编程错误:字符串格式化期间的参数数量错误,尝试过元组修复

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM