stephan
stephan

Reputation: 2403

using sqlite for the first time with python, error 'cursor is not defined'

I am new to Python and trying to create a simple phone book with sqlite3. My problem is I have a decorator that changes all strings to lower case, so when I call the displayPerson function, it changes everything to lowercase. My question is can I just return the tuple of attributes from ben.displayPerson into the 'conn.execute insert values' statement, rather than put ben.name, ben.age, ben.phone (which would ignore the decorator).

#A decorator to correct uppercase strings
def lowercasewrapper(func):
    def wrapper(*args, **kwargs):
        return [item.lower() for item in func(*args, **kwargs)]
    return wrapper

class People():
    numofpeeps = 0
    def __init__(self, name, age, phone, fblink):
        self.name=name
        self.age=age
        self.phone=phone
        self.fblink=fblink
        People.numofpeeps += 1


    @lowercasewrapper 
    def displayPerson(self): 
        return self.name, self.age, self.phone, self.fblink


ben=People("bEn", "10 years old", "503-405-4021", "http://facebook.com/ben")


#sqlite section

import sqlite3
conn = sqlite3.connect('addressbook.db')
cur=conn.cursor()
conn.execute('''
     CREATE TABLE people(name TEXT,
                   age TEXT, phone TEXT, fblink TEXT)''')
conn.execute("insert into people values (?, ?, ?, ?)", (ben.displayPerson))
cur.close()
conn.commit()
conn.close()

The error I'm getting in the python interpreter says:

line 33, in <module>
conn.execute("insert into people values (?, ?, ?, ?)", (ben.displayPerson))
ValueError: parameters are of unsupported type

Note: This works if I do conn.execute ("insert into people values (?, ?, ?, ?)", (ben.name, ben.age, ben.phone))

But, I want to use the decorator beforehand and I can't figure out how to do that.

Upvotes: 0

Views: 1677

Answers (1)

abarnert
abarnert

Reputation: 366103

The problem is that you're not calling ben.displayPerson, you're just referencing the method itself.

Just change it to this:

conn.execute("insert into people values (?, ?, ?, ?)", (ben.displayPerson()))

However, you should also get rid of those extra parentheses:

conn.execute("insert into people values (?, ?, ?, ?)", ben.displayPerson())

Putting a single value in parentheses does nothing, except to confuse a human reader into thinking you're wrapping the value in a 1-item tuple when you aren't.*


* There are a few cases where, if the value is a generator expression or a lambda expression, you need extra parentheses around it to keep the parser from being confused. And for very complex expressions, it may make things more readable. And of course for multiple values in a tuple, parentheses almost never hurt. But for a single, simple value, don't do it.

Upvotes: 2

Related Questions