Search code examples
pythonpython-3.xmysql-pythonmysql-connector

How do I get only the value of a column identified by a unique userid in MySQL? pls refer to Question for more detailed explanation


I'm currently writing an rpg game in python that uses a mysql database to store info on players. However, I've come across a problem.

Sample Code of How Database has been Set Up:

playerinfo Table
userID | money | xp |
  1    | 200   | 20 |
  2    | 100   | 10 |

I'm trying to select the amount of money with only the value. My select query right now is

SELECT money FROM playerinfo WHERE id = 1

The full code/function for collecting selecting the info is

def get_money_stats(user_id):
    global monresult
    remove_characters = ["{", "}", "'"]
    try:
        with connection.cursor() as cursor:
            monsql = "SELECT money FROM players WHERE userid = %s"
            value = user_id
            cursor.execute(monsql, value)
            monresult = str(cursor.fetchone())
    except Exception as e:
        print(f"An error Occurred>  {e}")

CURRENT OUTPUT:

{'money': 200}

DESIRED OUTPUT:

200

Basically, all I want to select is the INT/DATA from the player's row (identified by unique userid). How do I do that? The only solution I have is to replace the characters with something else but I don't really want to do that as it's incredibly inconvenient and messy. Is there another way to reformat/select the data?


Solution

  • It seems like that fetching one row gives you a dictionary of the selected columns with its values, which seems the correct approach to me. You should simply access the dictionary with the column that you want to retrieve:

    monresult = cursor.fetchone()['money']
    

    If you don't want to specify again the column (which you should) you could get the values of the dictionary as a list and retrieve the first one:

    monresult = list(cursor.fetchone().values())[0]
    

    I do not recommend the last approach because it's heavily dependent on the current status of the query and it may have to change if the query is changed.