简体   繁体   English

在python函数中使用sqlite3查询

[英]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). 每个页面访问和事件都有一个会话号和一个分配给它们的用户ID(以及其他一些信息)。

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. 现在,我的python脚本会在每次发生事件或页面访问时创建一个新用户-这不应该发生,因为某些事件和页面访问可能在同一会话中发生。

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. 因此,如果会话号已经存在,它将返回用户,如果结果为None则将该用户记录到数据库中。

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 我不确定python如何解释结果,所以我不知道如何定义if语句

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. 使用fetchone获取查询结果。

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. 我修复了SELECT语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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