gpt4 book ai didi

python - MySQLdb 游标.执行格式化程序

转载 作者:行者123 更新时间:2023-11-29 20:26:51 25 4
gpt4 key购买 nike

我正在使用 Python 和 MySQLdb 库。这是已经运行了很长时间的代码的一部分。

由于我们计划进行 SO 升级,所以我正在测试代码是否在其他 Ubuntu 版本中正确执行。

以下代码在 Ubuntu 12.04(我们的基准系统现在使用 Python 2.7.3)、Ubuntu 14.04.5 (Python 2.7.6) 中运行良好,但在 Ubuntu 16.04.1 (Python 2.7.12) 中运行不正常:

def updateOutputPath(path):
try:
# Connect to database
with closing(MySQLdb.connect(host=Constants.database_host,
user=Constants.database_user, passwd=Constants.database_passwd,
db=Constants.database_name)) as db:

# Create a cursor to execute queries
with closing(db.cursor()) as cursor:
# Execute query
cursor.execute('UPDATE configuration SET value=%s WHERE ' +
'property=\'OUTPUT_PATH\'', (path))
# Save changes in the database and close connection
db.commit()
except MySQLdb.Error, e:
print_exception('Database error', e)
print_db_query(cursor)

cursor.execute 语句中,我收到以下错误:并非所有参数在字符串格式化期间都已转换。

显然,我检查了唯一的参数是描述有效路径的有效字符串,就像在其他 SO 版本中执行时一样。

我可以创建一个字符串并将其传递给 cursor.execute 语句,问题就结束了,但我对这个问题很好奇。

知道为什么吗?

我还认为这可能与 python-mysqldb 库版本有关,而不是与 Python 版本有关。它的版本在Ubuntu 12.04中为1.2.3-1,在Ubuntu 14.04中为1.2.3-2,在Ubuntu 16.04中为1.3.7-1(我认为此更新与该操作系统版本中Mysql-server 5.7的使用有关) .

最佳答案

传递的参数必须是可迭代的,即列表或元组。所以它应该是 (path,) 而不是 (path)

cursor.execute('UPDATE configuration SET value=%s WHERE ' +
'property=\'OUTPUT_PATH\'', (path,))

>>> path = 'hello'
>>> a = (path)
>>> type(a)
<type 'str'>
>>> b = (path,)
>>> type(b)
<type 'tuple'>
>>> for x in a:
... print(x)
...
h
e
l
l
o
>>> for x in b:
... print(x)
...
hello

如果您传递 (path) ,它将作为路径字符串的每个字符进行迭代,而不是作为元组的项目进行迭代,正确的元组格式是 (path ,))

关于python - MySQLdb 游标.执行格式化程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39270265/

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