Python - 自动化MySQL查询:传递参数

2 投票
2 回答
2351 浏览
提问于 2025-04-15 17:46

这段代码运行得很好,但想把MySQL的代码改得更高效一些。

第一个情况是一个函数,它接收一个参数,然后从MySQL数据库中返回客户ID:

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

如果我们事先知道结果只会有一个输出,怎么能在我的getID_row里做到这一点,而不使用“for”循环呢?

第二个情况是这个函数在运行时用的是表名(‘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没有成功。

非常感谢大家的评论和建议。

2 个回答

0

很遗憾,你不能把表的名字当作参数来使用(可以参考这篇帖子)。你需要用Python的字符串操作来实现你想做的事情。

3

对于第一种情况(简单,但如果没有这一行就容易出现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)

要确保你对数据进行清理,因为游标不会自动处理这些。

撰写回答