Python操作MySQL报错:SQL语句未使用全部参数,数据无法存储
解决MySQL Connector插入时"Not all parameters were used"错误
问题根源
报错Not all parameters were used in the SQL statement的核心原因是:mysql.connector库仅支持%s作为所有数据类型的占位符,你在INSERT语句里用%i匹配整数类型是错误写法——该库不识别%i,导致参数无法正确绑定,最终数据无法插入。
修正后的代码
把INSERT语句里的所有%i替换成%s,mysql.connector会自动处理整数、字符串等类型的转换:
def dbconnect(): # 确保导入依赖模块 import mysql.connector from mysql.connector import errorcode try: db = mysql.connector.connect(host='localhost',user='SYSTEM', password='123456', database='billing_system') mycursor = db.cursor() mycursor.execute('CREATE TABLE IF NOT EXISTS bill( bill_no int NOT NULL PRIMARY KEY, c_name varchar(20) DEFAULT NULL, c_phone varchar(10) DEFAULT NULL, item varchar(20) DEFAULT NULL, rate int DEFAULT NULL, quantity int DEFAULT NULL, total int DEFAULT NULL);') # 所有占位符统一使用%s mycursor.execute('INSERT INTO bill (bill_no, c_name, c_phone, item, rate, quantity, total) VALUES (%s,%s,%s,%s,%s,%s,%s);', (b,a,c,i,r,q,s)) db.commit() except mysql.connector.Error as err: if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: print("用户名或密码错误") elif err.errno == errorcode.ER_BAD_DB_ERROR: print("数据库不存在") else: print(err) else: db.close()
额外注意事项
- 确认变量
b,a,c,i,r,q,s在dbconnect()函数的作用域内可访问,如果这些变量是外部定义的,需要通过参数传递或确保函数能读取到它们,否则会触发未定义变量错误。 - 确保代码顶部导入了
mysql.connector和errorcode,否则异常处理逻辑会报错。
内容的提问来源于stack exchange,提问作者Krishnakumar R
相关产品推荐
相关产品推荐

