我正在开发python模块。我的模块需要多次从数据库获取数据。我正在编写一个数据层类,其唯一目的是编写所有在同一位置访问数据库的函数,并从我模块的不同方法调用这些数据层类方法。
我尝试下面的代码:
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;
完成此操作后,我将在要访问数据库的类中创建同一类的实例,例如:
class example1:
def ex1():
do_something()
datalayerInstance = datalayer();
datalayerInstance.getEmpData();
但是,即使每次创建数据层类的实例时都执行以上操作,也会创建一个新的游标对象。我想避免这种情况,只创建一个游标对象,并在类中使用它。如何做到这一点?
另外,我尝试使用静态方法,但这也不能解决我的问题。
请帮忙,因为我是Python新手。
数据层
datalayerInstance = datalayer();
def get_datalayerinstance():
return datalayerInstance
example.py
import datalayer
datalayerInstance = get_datalayerinstance();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句