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

问题描述 投票:0回答:2

序列中的代码工作正常,但希望将 MySQL 代码改进为更有效的格式。

第一种情况是关于接收参数并从 MySQL 数据库返回 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这次不行了。

非常感谢所有意见和建议。

python mysql parameters automation
2个回答
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)

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


0
投票

不幸的是,您无法参数化表的名称(请参阅这篇文章)。您必须使用 Python 字符串操作来完成您在此处尝试的操作。

© www.soinside.com 2019 - 2024. All rights reserved.