Python向MySQL插入数据时的变量参数错误问题排查
MySQL动态指定表名插入数据报错解决
问题场景
尝试向不同MySQL表插入数据,将表名设为变量选择目标表:
- 方法1:直接在函数内写死参数,执行成功
- 方法2:将数据作为参数传入函数,执行失败,报错:
处理格式参数失败;Python的'set'类型无法转换为MySQL类型
方法1(成功代码)
import mysql.connector db = mysql.connector.connect(host="localhost", user="root", passwd="", database="test_base") mycursor = db.cursor() def testb(tablename): mycursor.execute(f"INSERT INTO `{tablename}` (Time, trade_ID, Price, Quantity) VALUES (%s,%s,%s,%s)", ('69922825334', '239938314','19.97000000','25.03000000')) db.commit() testb('test_table')
方法2(原错误代码)
def testb(tablename,Time, trade_ID, Price, Quantity): try: mycursor.execute(f"INSERT INTO `{tablename}` (Time, trade_ID, Price, Quantity) VALUES (%s,%s,%s,%s)", ({Time}, {trade_ID}, {Price}, {Quantity})) db.commit() except Exception as e: print(e) testb('test_table','1678462365478','240219532','17.25000000','4.00000000')
报错原因
错误代码里把参数用{}包裹,这在Python中会创建集合(set)类型,但mysql-connector的execute方法要求第二个参数必须是元组(tuple)或列表(list),集合类型无法被转换为MySQL支持的数据类型,因此报错。
修正后的代码
把参数部分的{}改成普通括号(创建元组)即可:
def testb(tablename, Time, trade_ID, Price, Quantity): try: mycursor.execute(f"INSERT INTO `{tablename}` (Time, trade_ID, Price, Quantity) VALUES (%s,%s,%s,%s)", (Time, trade_ID, Price, Quantity)) # 改为元组格式 db.commit() except Exception as e: print(e) testb('test_table','1678462365478','240219532','17.25000000','4.00000000')
也可以用列表形式传递参数:
[Time, trade_ID, Price, Quantity]
注意事项
- 表名用f-string拼接时必须加反引号
`,避免表名是SQL关键字或包含特殊字符导致语法错误 - SQL参数绑定必须使用元组/列表,不要用集合——集合是无序且去重的,不符合SQL参数的顺序要求
- 建议将数据库连接和游标管理改为局部变量或使用上下文管理器(
with语句),避免全局变量引发的并发问题
内容的提问来源于stack exchange,提问作者Mat
相关产品推荐
相关产品推荐

