【问题标题】:Impossible to insert data with PyMySQL when I use parameter使用参数时无法使用 PyMySQL 插入数据
【发布时间】:2013-04-25 20:09:11
【问题描述】:

我目前正在处理一个根据输入参数插入数据的基本查询,但我无法执行它。

cur.execute("INSERT INTO foo (bar1, bar2) values (?, ?)", (foo1, foo2))

我有这个错误信息:

Tkinter 回调 Traceback 中的异常(最近一次调用最后一次):
call 中的文件“/usr/lib/python3.2/tkinter/init.py”,第 1426 行 return self.func(*args) 文件“test.py”,第 9 行,在寄存器中 cur.execute("INSERT INTO foo (bar1, bar2) values (?,?)", (foo1, foo2)) 文件 “/usr/local/lib/python3.2/dist-packages/pymysql/cursors.py”,第 108 行, 在执行 query = query % escaped_args TypeError: unsupported operand type(s) for %: 'bytes' and 'tuple'

foo1 和 foo2 都是字符串类型。我试过%s,同样的错误。

【问题讨论】:

    标签: python python-3.x insert pymysql


    【解决方案1】:

    这似乎是cursors.py 中的bug。正如herehere 建议的那样,您应该在cursors.py 中替换这一行:

    query = query % conn.escape(args)
    

    有了这个:

    query = query.decode(charset) % conn.escape(args)
    

    如果它不起作用,试试这个:

    query = query.decode(charset) % escaped_args
    

    【讨论】:

    • 我在 cursors.py 中没有找到query = query % conn.escape(args) 这一行,所以我尝试将这一行query = query % escaped_args(与此post 相关)修改为你的行。但现在我有了这个:“TypeError:并非所有参数都在字符串格式化期间转换”
    • 非常感谢!它适用于query = query.decode(charset) % escaped_args 并使用%s 而不是?。 :D
    猜你喜欢
    • 2017-06-11
    • 2018-10-14
    • 1970-01-01
    • 2019-05-23
    • 2019-07-13
    • 2019-11-24
    • 1970-01-01
    • 2021-01-12
    • 2019-01-01
    相关资源
    最近更新 更多