Page 1 of 1

SQL mystery

Posted: Fri Feb 10, 2017 7:49 am
by quarkjuggler
Why does this work...

Code: Select all

import sqlite3
dconn = sqlite3.connect('w/usrdta')
johnCsr = dconn.cursor()
def b():
    johnCsr.execute('select * from formulas')
    x = johnCsr.fetchone()
    print(x)
def main():
    b()
    johnCsr.close()
    dconn.close()
...whereas this does not...

Code: Select all

import sqlite3
def b():
    johnCsr.execute('select * from formulas')
    x = johnCsr.fetchone()
    print(x)
def main():
    dconn = sqlite3.connect('w/usrdta')
    johnCsr = dconn.cursor()
    b()
    johnCsr.close()
    dconn.close()
...? If I use just x=2 instead of the SQL stuff, it acts as I would think it would. The message I get is
sqlite3.ProgrammingError: Cannot operate on a closed cursor.
Thanks, folks.

Re: SQL mystery

Posted: Fri Feb 10, 2017 8:05 am
by shuckle
In the latter nonworking example your cursor is local to each def, so when you call b() there is no open cursor.

In the working example your cursor is global so you can refer to it anywhere in the code.

Re: SQL mystery

Posted: Fri Feb 10, 2017 8:35 am
by quarkjuggler
Thanks, shuckle! I was under the impression that variables local to a function were available to functions called by that function, but obviously not. I've written about 2000 lines of code so far, so now I get to go back and do some proofreading!