mathieu
mathieu

Reputation: 107

Python, MySQL, load data from database, change it, save it again?

We're making a simple MUD as a sort of "learn how to program in Python" project. We'd like it to be persistent, so we have a MySQL database for the Python scripts to save to. However, we're sort of stuck right now with pulling an integer from the database, adding to it, and saving it once again. Here's my code:

initxp = cur.execute("SELECT Exp FROM CharactersDB WHERE ID=%s", name)
print "initxp is,", initxp
global xp
xp = int(initxp)
print "current xp is ", xp

global xpcounter
xpcounter = ("UPDATE CharactersDB SET Exp=%s WHERE ID=%s") #where is name variable


#save initial xp to db
cur.execute(xpcounter, (xp, name,))
db.commit()

#when you gain xp
def gainxp():
    global xp
    global xpcounter
    xp = xp + 10
    print name, "gains", xp, "xp!"
    #save new xp to db
    cur.execute(xpcounter, (xp, name,))
    db.commit()
    return xp


#save stats to the database,
#this funciton will be used in the character creation file

gainxp()

I don't have any errors, though I do have some weird things happening:

Firstly, when it prints the "initxp" variable, it returns with 1 every time. As does the "Current xp" line. So, when it enters into the gainxp() function, it just adds 1 to 10, saves the grand total of 11 and is on its merry way.

What we'd like to do is take that already saved 11 xp, add another 10 to it, save it, run it again and have another 10 added to it so we have 31xp, not a consistent 11 every time, which obviously defeats the purpose.

Thanks!

Upvotes: 0

Views: 347

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599490

cur.execute returns the number of rows affected - in your case, just 1 row, which is why it always returns 1. To get the actual value, you need to do cur.fetchone(), which will return a tuple of values - again, in your case, a tuple containing a single int.

Just an additional tip, since this is a 'learn Python' exercise: global variables are usually frowned on. You should pass xp explicitly into your gainxp function.

Upvotes: 1

Related Questions