[Tutor] pysqlite and functions

Alan Gauld alan.gauld at btinternet.com
Sat Apr 12 14:26:16 CEST 2008


"Dinesh B Vadhia" <dineshbvadhia at hotmail.com> wrote


Your code has several strangenesses in it but I'll focus on
your query for now...

################
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)
#############

You don;t say where db or field are defined but on the assumption
that this does work and you don;t get err9ors I'#ll ignore it for now.

###########
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
####################

This should work provided you really do have the names consistent
between the global variable cur and the name in the function.


> The error recieved is:
>
> NameError: global name 'cur' is not defined

> global con, curs, db.table

Note that you have cur in the code you posted and cvur in the
error message but you say curs here. Which is it?

3. Moving con and cur into the def statement results in the error:

The def statement is really just the first line, is that what you
mean? Or do you mean the function definition that follows the def?

Don't move them inside the function definition but rather pass
them in as parameters as you did with q, limit. However it shouldn't
really be necessary, but it is better style and aids reuse

> 4. The def getResults is not seeing con, curs and db.table
> even when declared as global.

Which suggests that either they are defined in another
module or function or you have inconsistent names
(maybe a case error?)

> 5. I wonder if this is something specific to pysqlite.

No, this is an error in your code somewhere.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list