设计Python/SQLite应用程序而不重复连接部分的正确方法是什么



im试图开发一个简单的应用程序,其中多个业务对象被保存到sqlite数据库中。我有几个业务对象,我想为它们编程保存/更新/删除方法。对于这些类中的每个类和方法,我总是创建一个新的连接。例如:

import sqlite3
db = "mydb.db"
class BusinessObject1:
...
def save_to_db(self, db):
conn = sqlite3.connect(db)
cur = conn.cursor()
with conn:
cur.execute("...")
def delete_from_db(self, db):
conn = sqlite3.connect(db)
cur = conn.cursor()
with conn:
cur.execute("...")
class BusinessObject2:
...
def save_to_db(self, db):
conn = sqlite3.connect(db)
cur = conn.cursor()
with conn:
cur.execute("...")
def delete_from_db(self, db):
conn = sqlite3.connect(db)
cur = conn.cursor()
with conn:
cur.execute("...")

它感觉不是一个好的设计解决方案(不是DRY(。有人能提出一个更好的设计方案吗?我有大约20个业务对象,每个对象有4-8个方法,还有一个记录表,其中包括所有这些对象。每次键入conn=sqlite3.connect(db(根本不是正确的方法。如果我决定改为MySQL或PostgreSQL,我需要重构整个项目。

谢谢!

然后您可能想要将连接处理程序与类对象分离,或者您可以按照上面的注释建议将连接放入类构造函数中。

如果由于某种原因不能同时执行这两项操作,则仍然可以向类中添加一个staticmethod来处理连接。这并不理想,但它仍然比您的解决方案更好:

@staticmethod
def create_connection(db_file):
conn = None
try:
with sqlite3.connect(db_file) as conn:
return conn
except sqlite3.Error as e:
print("Can't connect to database, error:", e, sep="n")
return conn

然后,您向其他方法添加一个参数,该参数将是返回的create_connection方法:

def save_to_db(self, connection):
cur = connection.cursor()
cur.execute("...")

通过这种方式,您可以将连接对象与类对象分离:

if __name__ == "__main__":
conn = BusinessObject1.create_connection(db)
b1 = BusinessObject1(...)
b1.save_to_db(conn)

最新更新