MySQLdb cursor.execute格式化程序

时间:2016-09-01 11:25:09

标签: python mysql ubuntu

我正在使用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的使用有关)

1 个答案:

答案 0 :(得分:0)

传递的参数需要是迭代的,即列表或元组。所以它应该是(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,))

相关问题