import MySQLdb as db def getConnection(): return db.connect( host = 'localhost', port = '3306', user = 'riz', passwd = 'password', db = 'blogdb' ) #Class that implements the with protocol class Cursor(): # method is called at the start of the with statement def __enter__(self): conn = getConnection() self.cursor = conn.cursor() return self.cursor # method is called at the end of the with statement # or if an exception is thrown within the with block def __exit__(self, type, value, traceback): self.cursor.close() if traceback: print "Type: ",type print "Value: ", value print "Trace: ", traceback return not traceback def getAllPosts(): with Cursor() as cursor: # __enter__ called result is stored in cursor #you can use the cursor here as normal cursor.execute('SELECT * FROM POSTS') return cursor.fetchall()
Sunday, 2 June 2013
With statement in Python
The with statement can be useful for writing reusable code. I have found especially useful when working with a database.
Subscribe to:
Post Comments (Atom)
-
Heres a quick example to show how annotations can be used as join points in AOP. The code below simply times the execution of any method wit...
-
In many database driven applications it can be useful to automate the testing of SQL against a real database. However setting up and maintai...
-
This post outlines the usages of datalakes and data warehouses. Source: https://www.kdnuggets.com/2015/09/data-lake-vs-data-warehouse...
No comments:
Post a Comment