Is there a way to creat a func that returns a cursor that can be used?

Joel Goldstick joel.goldstick at gmail.com
Mon Nov 12 07:25:43 EST 2012


On Mon, Nov 12, 2012 at 6:01 AM, Chris Angelico <rosuav at gmail.com> wrote:

> On Mon, Nov 12, 2012 at 9:45 PM, Khalid Al-Ghamdi <emailkgnow at gmail.com>
> wrote:
> > Is there a way to create a func that returns a cursor that can be used
> to execute sql statements?
>
> Yes, and you're almost there!
>
> > I tried this (after importing sqlite3), but it gave me the error below:
> >
> >>>> def connect():
> >     return cur
> >>>> connect()
> > <sqlite3.Cursor object at 0x0119EA20>
> >>>> cur.execute("select * from schedule")
> > Traceback (most recent call last):
> >   File "<pyshell#26>", line 1, in <module>
> >     cur.execute("select * from schedule")
> > NameError: name 'cur' is not defined
>
> All you need to do is make use of the return value. Try this instead:
>
> cur = connect()
>
> That takes the returned cursor object and binds it to the name 'cur'
> in global scope. You can then use 'cur.execute...' and it'll be the
> same object.
>
> As a side point, thank you for posting so clearly. It's easy to help
> when your code and traceback are all there!
>
> ChrisA
> --
> http://mail.python.org/mailman/listinfo/python-list
>

You asked this question yesterday.  I answered as did several others.  You
seem to be stuck on how values are returned from a function.

Chris gave you the same help that you got yesterday.

The cur variable within the function disappears when the function ends.
Read about python namespaces to learn more.  So, you need to return the cur
value in your function by using this statement:

    return cur

Then when you call connect() is will return the cur value.  You have to
name it like this:

    cur = connect()

You should go to python.org and read the tutorials, specifically about
functions.


good luck

-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20121112/497f1ce6/attachment.html>


More information about the Python-list mailing list