User avatar
quarkjuggler
Posts: 156
Joined: Wed Nov 27, 2013 4:37 am
Location: Aransas Pass, Texas, U.S.A.

SQL mystery

Fri Feb 10, 2017 7:49 am

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.
Statements resembling facts are IMO only. "he" means "he or she", etc. "Mother Nature" is an abstraction, not a real spirit.
John

shuckle
Posts: 565
Joined: Sun Aug 26, 2012 11:49 am
Location: Finland

Re: SQL mystery

Fri Feb 10, 2017 8:05 am

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.

User avatar
quarkjuggler
Posts: 156
Joined: Wed Nov 27, 2013 4:37 am
Location: Aransas Pass, Texas, U.S.A.

Re: SQL mystery

Fri Feb 10, 2017 8:35 am

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!
Statements resembling facts are IMO only. "he" means "he or she", etc. "Mother Nature" is an abstraction, not a real spirit.
John

Return to “Beginners”