1

I have the following class:

class SomeClass:
    def __init__(self, name, date):
        self.name = name
        self.date = date

Now I have a function in another module, which connects to a SQLite database and executes a query:

def getEntry(user):
    data = []
    connection = lite.connect(database)                                                                 
    with connection:                                                                 
        cur = connection.cursor()                                                    
        cur.execute("SELECT name, date FROM table WHERE column = ?", [user])
        events = cur.fetchall()                                                      
        # instantiate an instance of `SomeClass`
        return data

So how would I create an instance of SomeClass and pass name and date entries to my newly created instance?

2
  • Have you considered using a library to do this for you? Django is primarily a web framework, but its database support and ORM are phenomenal. Commented Nov 12, 2012 at 2:30
  • I'm already using cherryPy, don't really want to use Django on top of that. Can't be that hard to accomplish the above, or is it? Commented Nov 12, 2012 at 2:47

1 Answer 1

3

Since fetchall() returns a list of the rows, you should be able to do this (this should cover occasions where multiple results are returned as well):

for result in events:
    my_instance = SomeClass(result[0], result[1])
    # Do whatever you want to do with the instances, which looks like
    # it may be appending to data
    data.append(my_instance) # Or data.append(SomeClass(result[0], result[1]))

Can't test it right now, so apologies if it is way off :)

Sign up to request clarification or add additional context in comments.

2 Comments

Or return [SomeClass(*row) for row in cur]
@StevenRumbalski Even better :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.