gpt4 book ai didi

python - MySQL + Python : Not all arguments converted during string formatting

转载 作者:行者123 更新时间:2023-11-29 05:37:43 24 4
gpt4 key购买 nike

我正在尝试使用 cursor.execute(sql, args) 语法将 INSERT 插入到 MySQL 中。这是我目前拥有的:

# data = {...}
qmarks = ', '.join('?' * len(data))
query = "INSERT INTO title (%s) VALUES (%s)" %(qmarks, qmarks)
args = data.keys() + data.values()
print len(args), print len(data)
cursor.execute(query, args)

TypeError: not all arguments converted during string formatting

我检查了args(22)和quarks(11 x 2 = 22)的长度,它们似乎是一样的。是什么导致了这个错误,我需要更改什么?

更新:当我尝试使用 %s 进行字符串格式化时,它也会引发错误:

>>> data={'provider':'asdf', 'vendor_id': '1234'}
>>> format = ', '.join(['%s'] * len(data))
>>> query = "INSERT INTO title (%s) VALUES (%s)" %(format, format)
>>> query
'INSERT INTO title (%s, %s) VALUES (%s, %s)'
>>> cursor.execute(query, args)
Traceback (most recent call last):
raise errorclass, errorvalue
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the right syntax
to use near ''vendor_id', 'provider') VALUES ('1234', 'asdf')' at line 1")

我认为这与列定义是字符串这一事实有关:

INSERT INTO title ('vendor_id', 'provider') VALUES ('1234', 'asdf')

代替:

INSERT INTO title (vendor_id, provider) VALUES ('1234', 'asdf')

有没有办法在这里使用字符串格式,但传递一个变量而不是一个字符串?

最佳答案

假设您正在使用 MySQLdb,您希望在最终查询中有 %s,而不是 ?,您还需要直接在查询中输入列名而不是使用 %s 替换它们:

# data = {...}
columns = ', '.join(data.keys())
format = ', '.join(['%s'] * len(data))
query = "INSERT INTO title (%s) VALUES (%s)" % (columns, format)
cursor.execute(query, data.values())

关于python - MySQL + Python : Not all arguments converted during string formatting,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9337134/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com