【问题标题】:Python - automating MySQL query: passing parameterPython - 自动化 MySQL 查询:传递参数
【发布时间】:2016-06-08 01:47:33
【问题描述】:

序列中的代码运行良好,但希望将 MySQL 代码改进为更有效的格式。

第一种情况是关于一个函数,它接收一个参数并从 MySQL db 返回 customerID:

def clean_table(self,customerName):
    getCustomerIDMySQL="""SELECT customerID
    FROM customer
    WHERE customerName = %s;"""

    self.cursorMySQL.execute(getCustomerIDMySQL,(customerName))
    for getID_row in self.cursorMySQL:
        customerID=getID_row[0]

    return customerID

如果我们事先知道结果将只是一个输出,如何在不使用“for”语句的情况下将相同的内容放入我的 getID_row 中?

对于第二种情况,函数运行时带有表名('customer')...

def clean_tableCustomer(self):
    cleanTableQuery = """TRUNCATE TABLE customer;"""
    self.cursorMySQL.execute(cleanTableQuery)

    setIndexQuery = """ALTER TABLE customer AUTO_INCREMENT = 1;"""
    self.cursorMySQL.execute(setIndexQuery)

那么,如何将表名替换为通过函数传递的参数呢?以下是我尝试完成此操作的方法:

def clean_table(self,tableName):
    cleanTableQuery = """TRUNCATE TABLE %s;"""
    self.cursorMySQL.execute(cleanTableQuery,(tableName))

    setIndexQuery = """ALTER TABLE %s AUTO_INCREMENT = 1;"""
    self.cursorMySQL.execute(setIndexQuery,(tableName))

但这次 MySQL 没有工作。

非常感谢所有 cmets 和建议。

【问题讨论】:

    标签: python mysql parameters automation


    【解决方案1】:

    对于第一种情况(简单,但是在没有行的时候容易得到KeyError):

    customerID = self.cursorMySQL.fetchone()[0]
    

    更正确的是为游标类实现一个新方法:

    def autofetch_value(self, sql, args=None):
        """ return a single value from a single row or None if there is no row
        """
        self.execute(sql, args)
        returned_val = None
    
        row = self.fetchone()
        if row is not None:
            returned_val = row[0]
    
        return returned_val
    

    对于第二种情况:

    def clean_table(self,tableName):
        cleanTableQuery = """TRUNCATE TABLE %s;""" % (tableName,)
        self.cursorMySQL.execute(cleanTableQuery)
    
        setIndexQuery = """ALTER TABLE %s AUTO_INCREMENT = 1;""" % (tableName,)
        self.cursorMySQL.execute(setIndexQuery)
    

    确保对数据进行清理,因为光标不会。

    【讨论】:

      【解决方案2】:

      很遗憾,您不能对表的名称进行参数化(请参阅this post)。您将不得不使用 Python 字符串操作来执行您在此处尝试的操作。

      希望这会有所帮助,我花了一段时间才知道什么时候遇到这个问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-07-06
        • 2021-09-29
        • 1970-01-01
        相关资源
        最近更新 更多