[Tutor] pysqlite and functions
Dinesh B Vadhia
dineshbvadhia at hotmail.com
Sat Apr 12 10:26:56 CEST 2008
I'm using a pysqlite select statement within a def function and it's not working because (I suspect) the pysqlite variables are not being declared corrrectly to be used within a def function or the def function is not setup correctly. Here is the code followed by the errors:
**** code ****
con = sqlite3.connect(":memory:") # create database/table in memory
cur = con.cursor() # note: can use the nonstandard execute, executemany to avoid using Cursor object
query = "CREATE TABLE db.table(field.a INTEGER, field.b TEXT)"
cur.execute(query)
query = "INSERT INTO db.table(field.a, field.b) VALUES (?, ?)", data
cur.executemany(query)
def getResult(q, limit):
query = "SELECT field.b FROM db.table WHERE field.b LIKE '%s' LIMIT '%s'" %(q, limit)
for row in cur.execute(query):
print row
return
# main program
<snip>
..
q = <something>
limit = <something else>
getResult(q, limit) # call getResult with parameters q and limit
..
<snip>
**** end code ****
The error recieved is:
Traceback (most recent call last):
<snip>
for row in cur.execute(query):
NameError: global name 'cur' is not defined
Some notes:
1. The code works perfectly outside of a def function but I need to have it working within a def.
2. Clearly, everything inside getResults is private unless declared otherwise. As a quick and dirty to force it to work I declared
> global con, curs, db.table
.. but that results in the same error
3. Moving con and cur into the def statement results in the error:
Traceback (most recent call last):
<snip>
for row in cur.execute(query):
OperationalError: no such table: db.table
4. The def getResults is not seeing con, curs and db.table even when declared as global.
5. I wonder if this is something specific to pysqlite.
Cheers!
Dinesh
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080412/27aec8cd/attachment-0001.htm
More information about the Tutor
mailing list