Question

We're creating a basic MUD and want it to save/load from a MySQL database, as an initial command, we want to have an initial "Do you have a character?" prompt, we have the "no" part sorted out, and it successfully saves to the database. However, I'm having trouble with the "yes" part, more specifically, having it check the DB for a specific entry against user input to make sure it exists, and consequently load the data.

Here's my current code:

global name
name = ''
savename = ("INSERT INTO CharactersDB (ID) VALUES (%s)")
loadname = ("SELECT ID FROM CharactersDB WHERE ID=%s")

def newname():
    global name
    newchar = raw_input("Do you have a character? (y/n) ")
    if newchar == 'y':
        login = raw_input("Please enter your Character's name: ")
        logincheck = cur.execute(loadname, login)
        if login == logincheck:
            print "pass"
            print "Successfully loaded ", login, "from the database"

        else:
            print "Sorry, could not find you in the database"
            print "Or it just isn't working"

    else:
        name = raw_input("Please enter a new name: ")
        #save new name to the database
        cur.execute(savename, name)
        print "Name saved, you are now called ", name
        db.commit()
        return name

newname()

I don't have any errors, it just goes from the first if statement to the second one, saving the "new" name (though no changes are made to the db since the entry already exists)

Was it helpful?

Solution

Accord to the DB API the return value of cur.execute is undefined. So if you use

logincheck = cur.execute(loadname, login)

then your code will be relying on the particular behavior of your database adapter. MySQLdb for example, returns the primary key of the row selected (if it exists), or 0L if there is no such row. Nevertheless, I think it is better not to rely on this.

Your code will be a little more general if you instead stick to only those behaviors guaranteed by the DB API.

Instead you could use

cur.execute(loadname, login)
logincheck = cur.fetchone()

This will make logincheck a tuple (if a row exists) or the value None. If login is an ID in CharactersDB, then logincheck will look like the tuple (login, ), not the string login. If login is not an ID, then logincheck will be None.

So the if-statement could then look like this:

if logincheck is None:
    print("Sorry, could not find you in the database\nOr it just isn't working")
else:
    print("pass\nSuccessfully loaded {} from the database".format(login))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top