A S II M O V February 2016

Python/SQL - How the cursor functions

In my code I have a function that needs to return either a string or None depending on what is present in the database. However at the moment the result is a list with the string answer inside, or None. Is there any change that could be made that would result in just a string or None being returned, rather than having to index the list?

Here is the code:

def retrieve_player_name(username):
    param = [(username)]
    command = ("""
                SELECT username FROM players
                WHERE username = ?
                """)
    result = cur.execute(command, param).fetchone()
    if result is not None:
        return result[0]

Thanks in advance.

Answers


CL. February 2016

A database cursors fetches entire rows, not values. Even a row with a single value inside is still a row.

If you don't want to write row[0] multiple times, create a helper function execute_and_return_a_single_value_from_query().

Post Status

Asked in February 2016
Viewed 2,214 times
Voted 9
Answered 1 times

Search




Leave an answer