[英]MySQLdb cursor.execute formatter
我正在使用Python和MySQLdb庫。 這是已經使用了很多時間的代碼的一部分。
我正在測試代碼是否可以在其他Ubuntu版本中正確執行,因為我們計划進行SO升級。
以下代碼在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(我認為此更新與該OS版本中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,))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.