首页 > 解决方案 > 如何使用值填充 MySQL 表中的一列而不出现“未使用所有参数”编程错误?

问题描述

这是我使用的 python 3 代码:

import mysql.connector

mydb = mysql.connector.connect(
    host="localhost",
    user="username",        #I inserted the actual username here.
    passwd="password",      #I inserted the actual password here.
    database="mydatabase"
)

mycursor = mydb.cursor()
 #degrees is the table name, degreename is the column name. 
 #There are a total of two columns in the table, one for the id with should auto-increment, and the 'degreename' column that I'm trying to populate.

sql = "INSERT INTO degrees (degreename) VALUES (%s)" 
val = [
    ('Pharmacy'),
    ('Comp Sci'),
    ('Art'),
    ('History'),
    ('Psychology'),
    ('Medicine'),
    ('Sports'),
    ('Pottery')
]
mycursor.executemany(sql,val)
mydb.commit()

这是我得到的错误:

Traceback (most recent call last):
  File "newest.py", line 45, in <module>
    mycursor.executemany(sql,val)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/mysql/connector/cursor.py", line 668, in executemany
stmt = self._batch_insert(operation, seq_params)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/mysql/connector/cursor.py", line 613, in _batch_insert
raise errors.ProgrammingError(
mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement

我在编写 SQL 语句时缺少什么参数(或我犯的任何其他导致此错误的错误)?
谢谢你。

标签: mysqlpython-3.x

解决方案


您的元组中需要一个逗号才能将它们变成元组(请参阅MySQL 连接器手册)。这将起作用:

val = [
    ('Pharmacy',),
    ('Comp Sci',),
    ('Art',),
    ('History',),
    ('Psychology',),
    ('Medicine',),
    ('Sports',),
    ('Pottery',)
]

推荐阅读