我应该使用相同的对象进行独立的,不同的数据库操作吗?

问题描述 投票:0回答:1
class DB:
  def insert(self, data):
      #connect to database and insert the data into Table.

  def update(self, data):
      #connect to database and update the Table.

class EditInfo:
  def Insert_into_Table(self, data):
      self.object1 = DB() #created the object here
      self.object1.insert()

  def update_the_Table(self, data):
      self.object1.update() #Reusing the same object created before  

参考object1,为一个经常执行数据库操作的类创建一个对象(如self.object1)是一个好主意,并在多个方法中重用它(如Insert_into_Table(),update_the_Table())而不必费心删除它 ? 或者,我应该删除,调用__del__,之前创建的对象,并在需要时每次创建一个新对象?

python python-2.7
1个回答
2
投票

有一个非常低级别的对象用于访问数据库并且一次又一次地重复使用是合理的。事实上,我认为你最好拥有一个执行数据库访问的单例,并且每个会话只创建一次。唯一的问题是,您是否应该在数据库对象和业务逻辑之间有层(可能答案是肯定的)。

© www.soinside.com 2019 - 2024. All rights reserved.