में पुन: उपयोग करना चाहिए, मैं एक पायथन CGI स्क्रिप्ट लिख रहा हूं जो एक MySQL डेटाबेस से पूछेगा। मैं MySQLdb मॉड्यूल का उपयोग कर रहा हूँ। चूंकि डेटाबेस बार-बार queryed हो जाएगा, मैं इस समारोह ....क्या मुझे कर्सर को पाइथन MySQLdb मॉड्यूल
def getDatabaseResult(sqlQuery,connectioninfohere):
# connect to the database
vDatabase = MySQLdb.connect(connectioninfohere)
# create a cursor, execute and SQL statement and get the result as a tuple
cursor = vDatabase.cursor()
try:
cursor.execute(sqlQuery)
except:
cursor.close()
return None
result = cursor.fetchall()
cursor.close()
return result
मेरा प्रश्न है ... इस सबसे अच्छा अभ्यास है लिखा? क्या मुझे अपने कर्सर को अपने कार्यों में पुन: उपयोग करना चाहिए? उदाहरण के लिए। कौन सा बेहतर है ...
def callsANewCursorAndConnectionEachTime():
result1 = getDatabaseResult(someQuery1)
result2 = getDatabaseResult(someQuery2)
result3 = getDatabaseResult(someQuery3)
result4 = getDatabaseResult(someQuery4)
या getDatabaseeResult समारोह के साथ भाग सब एक साथ करते हैं और जैसे कुछ करना ..
def reusesTheSameCursor():
vDatabase = MySQLdb.connect(connectionInfohere)
cursor = vDatabase.cursor()
cursor.execute(someQuery1)
result1 = cursor.fetchall()
cursor.execute(someQuery2)
result2 = cursor.fetchall()
cursor.execute(someQuery3)
result3 = cursor.fetchall()
cursor.execute(someQuery4)
result4 = cursor.fetchall()
बस मुझे जो चाहिए था। धन्यवाद। – b10hazard
एक और छोटी सूचना: MySQLdb कर्सर निर्माण में डीबी को नेटवर्क अनुरोधों के साथ कुछ भी नहीं है, इसलिए यह सस्ता ऑपरेशन है। – Serge