Home > Software engineering >  SQLite3: Find a user based on their ID using a function
SQLite3: Find a user based on their ID using a function

Time:02-24

I want to make 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 = ? '''

As you can see, the function can be called by writing for example: UserGameDetails(3), and you will recieve all relevant information for the user with ID 3.

How can I make it so that my function knows that what the user puts in the brackets, is the UserID it is looking for?

CodePudding user response:

You may use execute() and bind the parameter. Note that your query should have a GROUP BY clause.

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.")
  • Related