解决Not all parameters were used in the SQL statement问题

版权声明:本文为博主原创文章,可以转载,但请添加原文链接。 https://blog.csdn.net/hwhsong/article/details/84064595

使用Python3连接MySQL数据库,执行INSERT语句时,遇到Not all parameters were used in the SQL statement错误,通常是由于没有正确使用MySQL的占位符导致的。

vals = ('C', '制造业', 35, '专用设备制造业', 600031, '三一重工')
cur.execute('''INSERT INTO industry_csrc 
        (category_code, category_name, industry_code, industry_name, company_code, company_name)
        VALUES (%s, %s, %d, %s, %d, %s)
 ''',  vals)

以上代码会执行出错,因为无论是数字(包括整数和浮点数)、字符串、日期时间或其他任意类型,都应该使用%s占位符。
修改上面的代码,可正确执行:

vals = ('C', '制造业', 35, '专用设备制造业', 600031, '三一重工')
cur.execute('''INSERT INTO industry_csrc 
        (category_code, category_name, industry_code, industry_name, company_code, company_name)
        VALUES (%s, %s, %s, %s, %s, %s)
 ''',  vals)

MySQL的参数标记与Python格式化字符串中使用的%s看起来相同,但这种关系只是巧合,其他数据库通常使用?来作为参数标记。

Note that the parameter markers used by mysql.connector may look the same as the %s used in Python string formatting but the relationship is only coincidental. Some database adapters like oursql and sqlite3 use ? as the parameter marker instead of %s.

猜你喜欢

转载自blog.csdn.net/hwhsong/article/details/84064595