Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-自动生成MySQL索引:传递参数_Python_Mysql_Parameters_Automation - Fatal编程技术网

Python-自动生成MySQL索引:传递参数

Python-自动生成MySQL索引:传递参数,python,mysql,parameters,automation,Python,Mysql,Parameters,Automation,我有一个新的改进版代码用于自动表索引的函数: def update_tableIndex(self,tableName): getIndexMySQLQuery = """SELECT numberID FROM %s;""" % (tableName,) updateIndexMySQLQuery = """UPDATE %s SET numberID=%s WHERE numberID=%s;""" % (tableName,) updateIn

我有一个新的改进版代码用于自动表索引的函数:

def update_tableIndex(self,tableName):
    getIndexMySQLQuery = """SELECT numberID
    FROM %s;""" % (tableName,)

    updateIndexMySQLQuery = """UPDATE %s 
    SET numberID=%s WHERE numberID=%s;""" % (tableName,)

    updateIndex=1
    self.cursorMySQL.execute(getIndexMySQLQuery)
    for row in self.cursorMySQL:
        indexID = row[0]
        self.cursorMySQL.execute(updateIndexMySQLQuery,(updateIndex,indexID))
        updateIndex+=1
虽然查询“getIndexMySQLQuery”可以很好地使用此语法,但另一个查询“updateIndexMySQLQuery”不起作用

有没有什么提示或建议来解决这个问题


非常感谢所有评论和建议。

第二个不起作用,因为您在查询字符串中使用了三个占位符,并且只提供了一个用于插值的变量

updateIndexMySQLQuery = """UPDATE %s 
SET numberID=%%s WHERE numberID=%%s;""" % (tableName,)

通过这种方式,字符串格式化机制不希望您提供3个值,因为百分号是“转义的”(我为答案的第一个版本感到羞耻)

使用%s替换开头的表名,但使用问号创建参数替换

updateIndexMySQLQuery = """UPDATE %s 
SET numberID=? WHERE numberID=?;""" % (tableName,)
...
    self.cursorMySQL.execute(updateIndexMySQLQuery,(updateIndex,indexID))

谢谢你的意见。我只是重新做了整个功能。以下是它的工作原理和外观:

def update_tableIndex(self,tableName,indexName):

    getIndexMySQLQuery = """SELECT %s
    FROM %s;""" % (indexName,tableName,)

    updateIndex=1
    self.cursorMySQL.execute(getIndexMySQLQuery)
    for row in self.cursorMySQL:
        indexID = row[0]

        updateIndexMySQLQuery = """UPDATE %s 
        SET %s=%s WHERE 
        %s=%s;""" % (tableName,
                     indexName,updateIndex,
                     indexName,indexID)

        self.cursorMySQL.execute(updateIndexMySQLQuery)
        updateIndex+=1
因此,唯一要做的就是将列名和表名作为参数通知。它允许对数据库中的所有其他表重复使用代码


希望这对其他人也有用。

问号占位符是否可以与MySQLdb一起使用(我知道它们在sqlite3中也可以使用)?它们可以与其他语言的mysql一起使用,所以我不明白为什么不。。。这是DBAPI2.0的要求,不是吗?我认为,在这种情况下,这是编程语言特定的db api规范,而不是与MySQL本身有关的东西(我可能错了)。我知道,这是python数据库api标准的一部分,但是我知道,MySQLdb的文档只提到百分比样式的占位符。我现在无法测试它,所以我将把它留给您:)查看dbapi,它说库决定使用什么,但需要以模块常量“格式”指定它。所以我猜测mysqldb的%s样式。遗憾的是,DBAPI需要一个参数类型,但它没有指定参数类型。您必须查看模块的
paramstyle
,以确定是哪个。一些DBAPI模块使用qmark样式。MySQLdb使用
格式
样式,不幸的是,这恰恰导致了参数化和字符串格式之间的混淆。这真是一团糟。不,这根本没用,事实上,这是极其有害的。不应将参数值连接到查询中,而应将其留给数据库API。如何确保所传递的参数被正确引用和转义?总之,不要那样做。