[Tutor] Connecting to a DB via a function call
Alan Gauld
alan.gauld at btinternet.com
Sun Nov 11 16:37:00 CET 2012
On 11/11/12 11:39, Khalid Al-Ghamdi wrote:
> Hi,
>
> Why is it that the following even though I call the below function? And
> how do I write a function that makes connection that I can use to query
> my DB?
The code and error don't align so it would help if we could see the
actual code that generated the error.
However there are some comments we can make about your function...
> def connect():
> conn = sqlite3.connect(':memory:')#use sch3.db or sch4.db ....
> cur = conn.cursor()
> cur.execute("create table schedule (teams integer, sn integer,
> badge integer ,name text, grp integer,\
> major text, track text, stage text, tc text)")
You are doing everything inside the function so when the function ends
all the local variables will be destroyed. Nothing is being passed back
to the outside world. You probably want a 'return cur'
Also by executing a create table inside the connect you seriously limit
the reuse of your connect() function. Are you sure you always want to
create a new schedule table every time you connect?
You can find some sample SQLite code in my tutorial (v2 only) under the
databases topic.
HTH,
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list