Sebastian
Sebastian

Reputation: 141

Using sqlite3 queries in python functions

I have a database that records users, events and page visits. Each page visit and event have a session number and a user ID assigned to them (as well as couple other things).

Right now my python script creates a new user each time there is an event or a page visit - that shouldn't happen since some events and page visits may happen during the same session.

I want to query the database to see whether there is a session with the same number already in the database, thus implying that the user is already in the database too. So if the session number already exists it should return the user and if the result is None then record the user to the database.

The function would look something like this:

def find_user(session)
    s = session
    c.execute('FROM event SELECT user WHERE session=?', s)

However I don't know what to do next. I am not sure how python interprets the result so I don't know how to define the if statement

Also, can I look through two tables for the same attribute (session) if they have no connection with each other directly?

Upvotes: 0

Views: 76

Answers (1)

falsetru
falsetru

Reputation: 368894

Use fetchone to get a query result.

def find_user(session)
    c.execute('SELECT user FROM event WHERE session=?', [session])
    row = c.fetchone()
    if row:
        return row[0]  # the first column: user
    else:
        return None

I fixed the SELECT statement little bit.

Upvotes: 2

Related Questions