I am developing a python module. My module needs getting data from database various times. I am writing a data-layer class with sole motive of writing all the functions which hits DB at same place and calling these data-layer class methods from different method of my module.
I tried below code:
class datalayer:
cur = None; #Cursor which would be used by all methods
def __init__(self):
conn=sqlite3.connect(DB_NAME);
cur=conn.cursor();
def getEmpData(self,flowId):
sql= "Select * from emp"
cur.execute(sql);
rows = cur.fetchall();
return rows;
def getManData(self,flowId):
sql= "Select * from manager"
cur.execute(sql);
rows = cur.fetchall();
return rows;
Once this is done I am creating instances of same class in classes where I want to hit DB, like:
class example1:
def ex1():
do_something()
datalayerInstance = datalayer();
datalayerInstance.getEmpData();
But even if a do above each time the instance of data-layer class is created a new cursor object would be created. I want to avoid this and create a cursor object just once and use the same through the class. How can this be achieved?
Also, I tried using static method, but that too is not solving my problem.
Please help as I am new to Python.