0

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?

1 Answer 1

2

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.

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

4 Comments

very nifty ... didn't know that the empty list evaluates to false!
@maxymoo, 0, False, empty container (string, list, tuple, dictionary, ..) are considered falsy value.
thank you for the fast answer, trying to implement right away
@falsetru sorry for asking directly but I see you are a python expert. Is there a way to write an object to the database using its attributes?

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.