简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM