SQLite3:使用函数根据用户 ID 查找用户

SQLite3: Find a user based on their ID using a function

我想做一个功能:

def UserGameDetails(UserID):

SQL = '''SELECT U.FirstName, U.LastName, COUNT(*) AS TotalGames
         FROM User U INNER JOIN Game G
         ON U.Id = G.UserId
         WHERE U.Id = ? '''

如您所见,可以通过编写例如:UserGameDetails(3)来调用该函数, 您将收到 ID 为 3 的用户的所有相关信息。

我怎样才能让我的函数知道用户放在括号中的是它正在寻找的 UserID?

您可以使用execute()并绑定参数。请注意,您的查询应该有一个 GROUP BY 子句。

SQL = '''SELECT U.FirstName, U.LastName, COUNT(*) AS TotalGames
         FROM User U INNER JOIN Game G
             ON U.Id = G.UserId
         WHERE U.Id = ?
         GROUP BY U.FirstName, U.LastName'''
id = 3
results = cursor.execute(SQL, (id,))

for row in results:
    first = row["FirstName"]
    last = row["LastName"]
    count = row["TotalGames"]
    print("User '" + first + " " + last + "' has played " + str(count) + " games.")