1

I use pypyodbc to read data from an ms sql server.

I am not sure if the cursor should be closed after any query or just once at the end and I could not find anything in the doc.

Example:

curs = con.cursor()

for id in id_list:
    curs.execute ('Select * from XXX where id = {}'.format (id))
    curs.fetchall ()
    # Write the data into the target...
    # curs.close() ???

curs.close()   

Is this correct?

thanks

user2735751
  • 33
  • 1
  • 6
  • close the cursor when you're done with it. – Paul H Jul 18 '17 at 20:24
  • If it implements the standard PEP for cursors (https://www.python.org/dev/peps/pep-0249/) , then related: https://stackoverflow.com/questions/5669878/when-to-close-cursors-using-mysqldb – OneCricketeer Jul 18 '17 at 20:26

1 Answers1

0

The with keyword is what you are looking for

with sqlite3.connect("db.db") as DB:
    cursor = DB.cursor()
    #...perform sql
# connection automatically closes
Joshua Nixon
  • 1,379
  • 2
  • 12
  • 25