python - Suggested practice for opening and closing cursors and connections -
the following common pattern have in code, , wondering more internals of cursors , connections.
cursor = connection.cursor() cursor.execute("set names utf8") cursor.execute(sql, args) results = cursor.fetchall() cursor.close() what difference between connection database , cursor? there downside of having open connection (for example, few minutes?). have un-closed cursors, effect? when executing multiple sql statements in succession, should new cursor created each time?
it depends on underlying implementation - cursor object inside driver.
in many db-api implementations, cursor object isn't "interesting" (i.e. can keep lots of them , let gc worry them), if haven't done query returns result sets.
i've not used python oracle, suspect (based on experience jdbc , others) not case in oracle. oracle jdbc drivers have server-side cursors vitally important close (there low default per-connection cursor limit; exceeding limit causes failure trying open another).
in oracle, relying on gc close cursors might hazardous if, example, open new cursor in loop , gc keeps them until looping function returns.
if true, might helpful use with-statement construction ensure cursor closed in timely fashion, if exception occurs.
update: can use contextlib.closing context-manager such as
with contextlib.closing(myconnection.cursor()) curs: curs.execute(... # if exception happens, cursor still closed # after block
Comments
Post a Comment