【发布时间】: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