Python 在使用图形搜索运行递归函数时,在何处保留DB连接状态?

Python 在使用图形搜索运行递归函数时,在何处保留DB连接状态?,python,graph,search,Python,Graph,Search,假设我们正在遍历存储在关系数据库表中的树 因此,我们编写了一个算法,从给定的顶部节点开始,然后对其子节点进行广度优先搜索 def search(node_id): global db cursor = db.cursor() select all rows from table where parent_id=node_id for each row in result search(row_id) 实际上,在实现它时,我们需要一个来自连接对象的

假设我们正在遍历存储在关系数据库表中的树

因此,我们编写了一个算法,从给定的顶部节点开始,然后对其子节点进行广度优先搜索

def search(node_id):
    global db
    cursor = db.cursor()
    select all rows from table where parent_id=node_id
    for each row in result
        search(row_id)
实际上,在实现它时,我们需要一个来自连接对象的游标对象

使用全局连接对象并从中取出游标与将连接对象作为参数传递给函数之间的权衡是什么

def search(db, node_id):
    cursor = db.cursor()
    select all rows from table where parent_id=node_id
    for each row in result
        search(db, row_id)

我认为最好的选择是保持光标作为对象字段。 大概是这样的:

class Sercher:
    def __init__(connection):
        self.cursor = connection.cursor()
        ...

    def search(self, node_id):
        ...
        # access:  self.cursor
        ...
        #recursion
        self.search(next_node_id)

我认为这更适合StackOverflow。这是一个一般的编程问题。你在说什么权衡?因为基于观点的问题应该是离题的,所以我认为你应该让问题更具体一些。