在python中上下文管理器之前或之后循环

问题描述 投票:0回答:1

我搜索了stackoverflow,找不到任何相关的标题。假设在python中,我想连接到数据库并执行一些查询。这是最好的方法。要在循环内声明with语句还是在循环外进行声明?它通常也适用于处理文件。为了更清楚起见,请参见以下2个变体。

另外,我想知道更好的方法来查找try和except语句,应该在启动上下文管理器之前还是之后(如我在下面所做的那样。)>

带循环前的语句

def wr_to_db(db_file):
    query_switch = 'insert into switches values (?, ?)'
    with sqlite3.connect(db_file) as conn:
        for data in read_switch_data():
            try:
                conn.execute(query_switch, data)
            except sqlite3.IntegrityError as e:
                print('Error occured: ', e)

带循环后的语句

def wr_to_db(db_file):
    query_switch = 'insert into switches values (?, ?)'
    for data in read_switch_data():
        with sqlite3.connect(db_file) as conn:
            try:
                conn.execute(query_switch, data)
            except sqlite3.IntegrityError as e:
                print('Error occured: ', e)

我搜索了stackoverflow,找不到任何相关的标题。假设在python中,我想连接到数据库并执行一些查询。这是最好的方法。用...内的语句声明...

python sqlite loops contextmanager
1个回答
0
投票

(我很惊讶没有人回答这个...)我认为您的第一个示例非常实用:您希望with()语句不在for循环之外。 with上下文管理器很有用,因为当您退出该块时,它会自动清理资源(关闭打开的文件或关闭/刷新建立的数据库连接)。因此,如果以第二种方式进行操作,并将上下文管理器inside

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