序列中的代码运行良好,但希望将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_行?在
对于第二种情况,函数运行时使用表名('customer')。。。在
^{pr2}$那么,如何将表名替换为通过函数传递的参数?我是如何做到这一点的:
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这次没用。在
我们非常感谢您的意见和建议。在
不幸的是,不能参数化表的名称(请参见this post)。您将不得不使用Python字符串操作来执行您在这里尝试的操作。在
希望这有帮助,我花了一段时间才发现我遇到了这个问题。在
对于第一种情况(简单,但在没有行时很容易获得keyrerror):
更正确的方法是为cursor类实现一个新方法:
^{pr2}$对于第二种情况:
确保清理数据,因为光标不会
相关问题 更多 >
编程相关推荐