Python操作MariaDB执行INSERT报ProgrammingError语法错误如何解决
问题原因
报错的根本原因是cursor.execute()的第二个参数要求传入可迭代的参数序列(元组/列表等),你所有尝试的写法里传入的都是单个字符串,没有封装成合法的单元素序列。Python中单个元素的元组声明必须在末尾加逗号,否则括号会被识别为普通的运算优先级符号,不会生成元组。
修正后的完整代码
# python3! import mariadb mydb = mariadb.connect( host="***(just wanted to exclude the domain)", port=25555, user="test", password="test", database="test" ) cursor = mydb.cursor() first = "test5" # 注意参数位置的元组末尾有逗号,标识这是单元素元组 cursor.execute("INSERT INTO contacts (firstname) VALUES (%s)", (first,)) mydb.commit() cursor.close() mydb.close()
其他可行写法参考
你之前尝试的两种写法调整参数格式后也可以正常运行:
- 写法1
sql = "INSERT INTO contacts (firstname) VALUES (%s)" val = ("test5",) # 末尾加逗号标识为元组 cursor.execute(sql, val)
- 写法2:用列表代替元组
first = "test5" cursor.execute("INSERT INTO contacts (firstname) VALUES (%s)", [first])
内容的提问来源于stack exchange,提问作者Nicktron
相关产品推荐
相关产品推荐

