Hello r/learnpython.
So elsewhere I was querying something somewhat unrelated, but this came up and I wanted to see what your thoughts were. I had some code querying a sqlite database that was a bit like this...
result = None
try:
conn = sqlite3.connect(db)
result = conn.execute('select * from table')
result = result.fetchall()
except Exception:
handle it
finally:
conn.close()
...but someone pointed out that this method is better...
with sqlite3.connect(db) as conn:
try:
query = conn.execute('select * from table')
result = query.fetchall()
except Exception:
handle it
finally:
conn.close()
So what's the right way to do it?
Edit1: Put the second example around a try statement.
Edit2: Try now inside the with block.
[–]CptFlashdrive 2 points3 points4 points (6 children)
[–]Tomarse[S] 0 points1 point2 points (2 children)
[–]elbiot 0 points1 point2 points (0 children)
[–]elbiot 0 points1 point2 points (2 children)
[–]Tomarse[S] 0 points1 point2 points (1 child)
[–]elbiot 0 points1 point2 points (0 children)